Programs & Examples On #Gerrit

Gerrit is a web based code review and project management for Git based projects.

Gerrit error when Change-Id in commit messages are missing

under my .git/hooks folder, some sample files were missing. like commit-msg,post-commit.sample,post-update.sample...adding these files resolved my change id missing issue.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

With Spring can I make an optional path variable?

Check this Spring 3 WebMVC - Optional Path Variables. It shows an article of making an extension to AntPathMatcher to enable optional path variables and might be of help. All credits to Sebastian Herold for posting the article.

Sort a list of lists with a custom compare function

>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]

The above works. Are you doing something different?

Notice that your key function is just sum; there's no need to write it explicitly.

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

Adding one more answer for Windows users. If none of this solves the problems.

Do not add space before or after =

-DgroupId= com.company.module //Wrong , Watch the space after the equal to 
-DgroupId=com.company.module //Right 

Its better to put everything inside double quotes, like "-DgroupId=com.." This will give you exact error rather than some random error.

Weird that , maven does not even care to mention this in the documentation.

Sort & uniq in Linux shell

sort -u will be slightly faster, because it does not need to pipe the output between two commands

also see my question on the topic: calling uniq and sort in different orders in shell

Breaking to a new line with inline-block?

Here is another solution (only relevant declarations listed):

.text span {
   display:inline-block;
   margin-right:100%;
}

When the margin is expressed in percentage, that percentage is taken from the width of the parent node, so 100% means as wide as the parent, which results in the next element getting "pushed" to a new line.

How to resize JLabel ImageIcon?

And what about it?:

ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);

From: Resize a picture to fit a JLabel

Escaping single quote in PHP when inserting into MySQL

You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"

where $val is the data which is troubling you.

Validate phone number using angular js

<form name = "numberForm">
    <div>
    <input type="number"
           placeholder = "Enter your phonenumber"
           class = "formcontroll"
           name = "numbers"
           ng-minlength = "10"
           ng-maxlength = "10"
           ng-model="phno" required/>
           <p ng-show = "numberForm.numbers.$error.required ||
                       numberForm.numbers.$error.number">
                       Valid phone number is required</p>
            <p ng-show = "((numberForm.numbers.$error.minlength ||
                        numberForm.numbers.$error.maxlength)
                        && numberForm.numbers.$dirty)">
                        Phone number should be 10 digits</p><br><br>
       </div>
   </form>

How to check heap usage of a running JVM from the command line?

For Java 8 you can use the following command line to get the heap space utilization in kB:

jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'

The command basically sums up:

  • S0U: Survivor space 0 utilization (kB).
  • S1U: Survivor space 1 utilization (kB).
  • EU: Eden space utilization (kB).
  • OU: Old space utilization (kB).

You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.

Writing a pandas DataFrame to CSV file

To delimit by a tab you can use the sep argument of to_csv:

df.to_csv(file_name, sep='\t')

To use a specific encoding (e.g. 'utf-8') use the encoding argument:

df.to_csv(file_name, sep='\t', encoding='utf-8')

Get current index from foreach loop

You have two options here, 1. Use for instead for foreach for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:

int i = 0; // for index
foreach (var row in list)
{
    bool IsChecked;// assign value to this variable
    if (IsChecked)
    {    
       // use i value here                
    }
    i++; // will increment i in each iteration
}

Moment Js UTC to Local Time

let utcTime = "2017-02-02 08:00:13.567";
var offset = moment().utcOffset();
var localText = moment.utc(utcTime).utcOffset(offset).format("L LT");

Try this JsFiddle

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

To add to the previous answer, an extreme way of "cleaning" your project is to delete it (that is deleting its reference from the workspace, not deleting the actual files), and then re-import it.
Sometimes, it helps...

How to use mongoose findOne

You might want to consider using console.log with the built-in "arguments" object:

console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

Access a URL and read Data with R

Often data on webpages is in the form of an XML table. You can read an XML table into R using the package XML.

In this package, the function

readHTMLTable(<url>)

will look through a page for XML tables and return a list of data frames (one for each table found).

Collections.emptyList() returns a List<Object>?

The issue you're encountering is that even though the method emptyList() returns List<T>, you haven't provided it with the type, so it defaults to returning List<Object>. You can supply the type parameter, and have your code behave as expected, like this:

public Person(String name) {
  this(name,Collections.<String>emptyList());
}

Now when you're doing straight assignment, the compiler can figure out the generic type parameters for you. It's called type inference. For example, if you did this:

public Person(String name) {
  List<String> emptyList = Collections.emptyList();
  this(name, emptyList);
}

then the emptyList() call would correctly return a List<String>.

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

'NoneType' object is not subscriptable?

list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]

def printer(*lists):
    for _list in lists:
        for ele in _list:
            print(ele, end = ", ")
        print()

printer(list1, list2, list3)

I can't understand why this JAXB IllegalAnnotationException is thrown

for me this error was actually caused by a field falsely declared as public instead of private.

SQL error "ORA-01722: invalid number"

If you do an insert into...select * from...statement, it's easy to get the 'Invalid Number' error as well.

Let's say you have a table called FUND_ACCOUNT that has two columns:

AID_YEAR  char(4)
OFFICE_ID char(5)

And let's say that you want to modify the OFFICE_ID to be numeric, but that there are existing rows in the table, and even worse, some of those rows have an OFFICE_ID value of ' ' (blank). In Oracle, you can't modify the datatype of a column if the table has data, and it requires a little trickery to convert a ' ' to a 0. So here's how to do it:

  1. Create a duplicate table: CREATE TABLE FUND_ACCOUNT2 AS SELECT * FROM FUND_ACCOUNT;
  2. Delete all the rows from the original table: DELETE FROM FUND_ACCOUNT;
  3. Once there's no data in the original table, alter the data type of its OFFICE_ID column: ALTER TABLE FUND_ACCOUNT MODIFY (OFFICE_ID number);

  4. But then here's the tricky part. Because some rows contain blank OFFICE_ID values, if you do a simple INSERT INTO FUND_ACCOUNT SELECT * FROM FUND_ACCOUNT2, you'll get the "ORA-01722 Invalid Number" error. In order to convert the ' ' (blank) OFFICE_IDs into 0's, your insert statement will have to look like this:

INSERT INTO FUND_ACCOUNT (AID_YEAR, OFFICE_ID) SELECT AID_YEAR, decode(OFFICE_ID,' ',0,OFFICE_ID) FROM FUND_ACCOUNT2;

Required attribute on multiple checkboxes with the same name?

var verifyPaymentType = function () {
   //coloque os checkbox dentro de uma div com a class checkbox
  var inputs =  window.jQuery('.checkbox').find('input');
  var first = inputs.first()[0];

  inputs.on('change', function () {
    this.setCustomValidity('');
  });

  first.setCustomValidity( window.jQuery('.checkbox').find('input:checked').length === 0 ? 'Choose one' : '');
}

window.jQuery('#submit').click(verifyPaymentType);

}

Is there a command like "watch" or "inotifywait" on the Mac?

Facebook's watchman, available via Homebrew, also looks nice. It supports also filtering:

These two lines establish a watch on a source directory and then set up a trigger named "buildme" that will run a tool named "minify-css" whenever a CSS file is changed. The tool will be passed a list of the changed filenames.

$ watchman watch ~/src

$ watchman -- trigger ~/src buildme '*.css' -- minify-css

Notice that the path must be absolute.

Javascript swap array elements

what about Destructuring_assignment

var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]

which can also be extended to

[src order elements] => [dest order elements]

window.onload vs $(document).ready()

window.onload: A normal JavaScript event.

document.ready: A specific jQuery event when the entire HTML has been loaded.

Remote debugging Tomcat with Eclipse

Can you check if this works?

JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

catalina.sh jpda start

Set session variable in laravel

In Laravel 6.x

// Retrieve a piece of data from the session...
$value = session('key');

// Specifying a default value...
$value = session('key', 'default');

// Store a piece of data in the session...
session(['key' => 'value']);

https://laravel.com/docs/6.x/session

Class Not Found Exception when running JUnit test

In my case I had a wrong maven directory structure.

Which should be like:

/src/test/java/ com.myproject.server.MyTest

After I fixed that - everything worked like a charm.

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

What is the difference between Scala's case class and class?

Nobody mentioned that case class companion object has tupled defention, which has a type:

case class Person(name: String, age: Int)
//Person.tupled is def tupled: ((String, Int)) => Person

The only use case I can find is when you need to construct case class from tuple, example:

val bobAsTuple = ("bob", 14)
val bob = (Person.apply _).tupled(bobAsTuple) //bob: Person = Person(bob,14)

You can do the same, without tupled, by creating object directly, but if your datasets expressed as list of tuple with arity 20(tuple with 20 elements), may be using tupled is your choise.

Throwing multiple exceptions in a method of an interface in java

I think you are asking for something like the code below:

public interface A
{
    void foo() 
        throws AException;
}

public class B
    implements A
{
    @Overrides 
    public void foo()
        throws AException,
               BException
    {
    }
}

This will not work unless BException is a subclass of AException. When you override a method you must conform to the signature that the parent provides, and exceptions are part of the signature.

The solution is to declare the the interface also throws a BException.

The reason for this is you do not want code like:

public class Main
{
    public static void main(final String[] argv)
    {
        A a;

        a = new B();

        try
        {
            a.foo();
        }
        catch(final AException ex)
        {
        }
        // compiler will not let you write a catch BException if the A interface
        // doesn't say that it is thrown.
    }
}

What would happen if B::foo threw a BException? The program would have to exit as there could be no catch for it. To avoid situations like this child classes cannot alter the types of exceptions thrown (except that they can remove exceptions from the list).

MySQL, create a simple function

Try to change CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR this portion to CREATE FUNCTION F_TEST(PID INT) RETURNS TEXT

and change the following line too.

DECLARE NAME_FOUND TEXT DEFAULT "";

It should work.

How do I insert non breaking space character &nbsp; in a JSF page?

Eventually, you can try this one, if just using &nbsp; fails...

<h:outputText value="& nbsp;" escape="false"/>

(like Tom, I added a space between & and nbsp; )

Batch program to to check if process exists

This is a one line solution.

It will run taskkill only if the process is really running otherwise it will just info that it is not running.

tasklist | find /i "notepad.exe" && taskkill /im notepad.exe /F || echo process "notepad.exe" not running.

This is the output in case the process was running:

notepad.exe           1960 Console                   0    112,260 K
SUCCESS: The process "notepad.exe" with PID 1960 has been terminated.

This is the output in case not running:

process "notepad.exe" not running.

One liner to check if element is in the list

There is a boolean contains(Object obj) method within the List interface.

You should be able to say:

if (list.contains("a")) {
    System.out.println("It's there");
}

According to the javadoc:

boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

Easier way to debug a Windows service

When developing and debugging a Windows service I typically run it as a console application by adding a /console startup parameter and checking this. Makes life much easier.

static void Main(string[] args) {
    if (Console.In != StreamReader.Null) {
        if (args.Length > 0 && args[0] == "/console") {
            // Start your service work.
        }
    }
}

Git - Pushing code to two remotes

To send to both remote with one command, you can create a alias for it:

git config alias.pushall '!git push origin devel && git push github devel'

With this, when you use the command git pushall, it will update both repositories.

How to go to a URL using jQuery?

why not using?

location.href='http://www.example.com';

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    function goToURL() {_x000D_
      location.href = 'http://google.it';_x000D_
_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <a href="javascript:void(0)" onclick="goToURL(); return false;">Go To URL</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

SUM of grouped COUNT in SQL Query

After the query, run below to get the total row count

select @@ROWCOUNT

Call Jquery function

calling a function is simple ..

 myFunction();

so your code will be something like..

 $(function(){
     $('#elementID').click(function(){
         myFuntion();  //this will call your function
    });
 });

  $(function(){
     $('#elementID').click( myFuntion );

 });

or with some condition

if(something){
   myFunction();  //this will call your function
}

How to remove new line characters from data rows in mysql?

update mytable set title=trim(replace(REPLACE(title,CHAR(13),''),CHAR(10),''));

Above is working for fine.

Change background colour for Visual Studio

File-> Preferences-> Settings.

Find workbench.colorCustomizations object, change its editor.background property and save (you will see the results immediately — no need to restart vs code). Or you just can copy my current config file vs code config gist.

Can't create project on Netbeans 8.2

I had the same issue,

  • Quit Netbeans.
  • Delete the JDK9 file in : /Library/Java/JavaVirtualMachines
  • Install the JDK8 : Download link

Good luck :)

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

How do I make a LinearLayout scrollable?

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|left"
        android:orientation="vertical">

        Your views go here...

    </LinearLayout>

</ScrollView>

MySQL duplicate entry error even though there is no duplicate entry

Try with auto increment:

CREATE TABLE IF NOT EXISTS `my_table` (
   `number` int(11) NOT NULL AUTO_INCREMENT,
   `name` varchar(50) NOT NULL,
   `money` int(11) NOT NULL,
    PRIMARY KEY (`number`,`name`)
) ENGINE=MyISAM;

Squash my last X commits together using Git

To squash the last 10 commits into 1 single commit:

git reset --soft HEAD~10 && git commit -m "squashed commit"

If you also want to update the remote branch with the squashed commit:

git push -f

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Get properties and values from unknown object

void Test(){
    var obj = new{a="aaa", b="bbb"};

    var val_a = obj.GetValObjDy("a"); //="aaa"
    var val_b = obj.GetValObjDy("b"); //="bbb"
}
//create in a static class
static public object GetValObjDy(this object obj, string propertyName)
{            
     return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}

How to read a file byte by byte in Python and how to print a bytelist as a binary?

To answer the second part of your question, to convert to binary you can use a format string and the ord function:

>>> byte = 'a'
>>> '{0:08b}'.format(ord(byte))
'01100001'

Note that the format pads with the right number of leading zeros, which seems to be your requirement. This method needs Python 2.6 or later.

Shell Script: Execute a python program from within a shell script

Imho, writing

python /path/to/script.py

Is quite wrong, especially in these days. Which python? python2.6? 2.7? 3.0? 3.1? Most of times you need to specify the python version in shebang tag of python file. I encourage to use

#!/usr/bin/env python2 #or python2.6 or python3 or even python3.1
for compatibility.

In such case, is much better to have the script executable and invoke it directly:

#!/bin/bash

/path/to/script.py

This way the version of python you need is only written in one file. Most of system these days are having python2 and python3 in the meantime, and it happens that the symlink python points to python3, while most people expect it pointing to python2.

Python, creating objects

Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -

# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
    name = "Unknown name"
    age = 0
    major = "Unknown major"

You can create a make_student function by explicitly assigning the attributes to a new instance of Student -

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    return student

But it probably makes more sense to do this in a constructor (__init__) -

class Student(object):
    def __init__(self, name="Unknown name", age=0, major="Unknown major"):
        self.name = name
        self.age = age
        self.major = major

The constructor is called when you use Student(). It will take the arguments defined in the __init__ method. The constructor signature would now essentially be Student(name, age, major).

If you use that, then a make_student function is trivial (and superfluous) -

def make_student(name, age, major):
    return Student(name, age, major)

For fun, here is an example of how to create a make_student function without defining a class. Please do not try this at home.

def make_student(name, age, major):
    return type('Student', (object,),
                {'name': name, 'age': age, 'major': major})()

Making a DateTime field in a database automatic?

Yes, here's an example:

CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )

You can INSERT into the table without indicating the createdDate and updatedDate columns:

INSERT INTO myTable (col1) VALUES (1)

Or use the keyword DEFAULT:

INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)

Then create a trigger for updating the updatedDate column:

CREATE TRIGGER dbo.updateMyTable 
ON dbo.myTable
FOR UPDATE 
AS 
BEGIN 
    IF NOT UPDATE(updatedDate) 
        UPDATE dbo.myTable SET updatedDate=GETDATE() 
        WHERE col1 IN (SELECT col1 FROM inserted) 
END 
GO

Transfer data from one database to another database

You can use visual studio 2015. Go to Tools => SQL server => New Data comparison

Select source and target Database.

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

How to add text to a WPF Label in code?

You can use the Content property on pretty much all visual WPF controls to access the stuff inside them. There's a heirarchy of classes that the controls belong to, and any descendants of ContentControl will work in this way.

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

Revert a jQuery draggable object back to its original container on out event of droppable

In case anyone's interested, here's my solution to the problem. It works completely independently of the Draggable objects, by using events on the Droppable object instead. It works quite well:

$(function() {
    $(".draggable").draggable({
        opacity: .4,
        create: function(){$(this).data('position',$(this).position())},
        cursor:'move',
        start:function(){$(this).stop(true,true)}
    });

    $('.active').droppable({
        over: function(event, ui) {
            $(ui.helper).unbind("mouseup");
        },
        drop:function(event, ui){
            snapToMiddle(ui.draggable,$(this));
        },
        out:function(event, ui){
            $(ui.helper).mouseup(function() {
                snapToStart(ui.draggable,$(this)); 
            });
        }
    });
}); 

function snapToMiddle(dragger, target){
    var topMove = target.position().top - dragger.data('position').top + (target.outerHeight(true) - dragger.outerHeight(true)) / 2;
    var leftMove= target.position().left - dragger.data('position').left + (target.outerWidth(true) - dragger.outerWidth(true)) / 2;
    dragger.animate({top:topMove,left:leftMove},{duration:600,easing:'easeOutBack'});
}
function snapToStart(dragger, target){
    dragger.animate({top:0,left:0},{duration:600,easing:'easeOutBack'});
}

Setting Windows PATH for Postgres tools

All you need to do is to change the PATH variable to include the bin directory of your PostgreSQL installation.

An explanation on how to change environment variables is here:

http://support.microsoft.com/kb/310519
http://www.computerhope.com/issues/ch000549.htm

To verify that the path is set correctly, you can use:

echo %PATH%

on the commandline.

Find an element in DOM based on an attribute value

We can use attribute selector in DOM by using document.querySelector() and document.querySelectorAll() methods.

for yours:

document.querySelector("[myAttribute='aValue']");

and by using querySelectorAll():

document.querySelectorAll("[myAttribute='aValue']");

In querySelector() and querySelectorAll() methods we can select objects as we select in "CSS".

More about "CSS" attribute selectors in https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

Carriage return and Line feed... Are both required in C#?

System.Environment.NewLine is the constant you are looking for - http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx which will provide environment specific combination that most programs on given OS will consider "next line of text".

In practice most of the text tools treat all variations that include \n as "new line" and you can just use it in your text "foo\nbar". Especially if you are trying to construct multi-line format strings like $"V1 = {value1}\nV2 = {value2}\n". If you are building text with string concatenation consider using NewLine. In any case make sure tools you are using understand output the way you want and you may need for example always use \r\n irrespective of platform if editor of your choice can't correctly open files otherwise.

Note that WriteLine methods use NewLine so if you plan to write text with one these methods avoid using just \n as resulting text may contain mix of \r\n and just \n which may confuse some tools and definitely does not look neat.

For historical background see Difference between \n and \r?

How to make a radio button look like a toggle button

Inspired by Michal B. answer. If you use bootstrap..

_x000D_
_x000D_
label.btn {_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
label.btn input {_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
label.btn span {_x000D_
  text-align: center;_x000D_
  padding: 6px 12px;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
label.btn input:checked+span {_x000D_
  background-color: rgb(80, 110, 228);_x000D_
  color: #fff;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
<div>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>One</span></label>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Two</span></label>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Three</span></label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I create numbered map markers in Google Maps V3?

Based on @dave1010 answer but with updated https links.

Numbered marker:

https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000

Text marker:

https://chart.googleapis.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|Marker

How do I use typedef and typedef enum in C?

typedef enum state {DEAD,ALIVE} State;
|     | |                     | |   |^ terminating semicolon, required! 
|     | |   type specifier    | |   |
|     | |                     | ^^^^^  declarator (simple name)
|     | |                     |    
|     | ^^^^^^^^^^^^^^^^^^^^^^^  
|     |
^^^^^^^-- storage class specifier (in this case typedef)

The typedef keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern or static is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.

After the above declaration, the State identifier becomes an alias for the type enum state {DEAD,ALIVE}. The declaration also provides that type itself. However that isn't typedef doing it. Any declaration in which enum state {DEAD,ALIVE} appears as a type specifier introduces that type into the scope:

enum state {DEAD, ALIVE} stateVariable;

If enum state has previously been introduced the typedef has to be written like this:

typedef enum state State;

otherwise the enum is being redefined, which is an error.

Like other declarations (except function parameter declarations), the typedef declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:

typedef unsigned long ulong, *ulongptr;
|     | |           | |  1 | |   2   |
|     | |           | |    | ^^^^^^^^^--- "pointer to" declarator
|     | |           | ^^^^^^------------- simple declarator
|     | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier

This typedef introduces two type names ulong and ulongptr, based on the unsigned long type given in the specifier-qualifier list. ulong is just a straight alias for that type. ulongptr is declared as a pointer to unsigned long, thanks to the * syntax, which in this role is a kind of type construction operator which deliberately mimics the unary * for pointer dereferencing used in expressions. In other words ulongptr is an alias for the "pointer to unsigned long" type.

Alias means that ulongptr is not a distinct type from unsigned long *. This is valid code, requiring no diagnostic:

unsigned long *p = 0;
ulongptr q = p;

The variables q and p have exactly the same type.

The aliasing of typedef isn't textual. For instance if user_id_t is a typedef name for the type int, we may not simply do this:

unsigned user_id_t uid;  // error! programmer hoped for "unsigned int uid". 

This is an invalid type specifier list, combining unsigned with a typedef name. The above can be done using the C preprocessor:

#define user_id_t int
unsigned user_id_t uid;

whereby user_id_t is macro-expanded to the token int prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.

Among the disadvantages that it doesn't work well for derived types:

 #define silly_macro int *

 silly_macro not, what, you, think;

This declaration doesn't declare what, you and think as being of type "pointer to int" because the macro-expansion is:

 int * not, what, you, think;

The type specifier is int, and the declarators are *not, what, you and think. So not has the expected pointer type, but the remaining identifiers do not.

And that's probably 99% of everything about typedef and type aliasing in C.

Make button width fit to the text

Pretty late and not sure if this was available when the question was asked, set width: auto;

Seems to do the trick

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

How can I convert a stack trace to a string?

Arrays.toString(thrown.getStackTrace())

Is the easiest way to convert the result into String I am using this in my program to print the stack trace

LOGGER.log(Level.SEVERE, "Query Builder Issue Stack Trace : {0} ,Message : {1} objid {2}", new Object[]{Arrays.toString(e.getStackTrace()), e.getMessage(),objId});

Failed to find Build Tools revision 23.0.1

Either install v23.0.1 of the build tools (the fifth row in your screenshot), or change your code to use the build tools version you already have installed (v23.0.3). This can be specified in your app's build.gradle file:

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        ...
    }
}

As per duncanc4's comment below,

The build.gradle file you want to edit is in the android/app folder within your project directory.

libstdc++.so.6: cannot open shared object file: No such file or directory

For Fedora use:

yum install libstdc++44.i686

You can find out which versions are supported by running:

yum list all | grep libstdc | grep i686

Spark: subtract two DataFrames

I tried subtract, but the result was not consistent. If I run df1.subtract(df2), not all lines of df1 are shown on the result dataframe, probably due distinct cited on the docs.

This solved my problem: df1.exceptAll(df2)

What is the difference between varchar and varchar2 in Oracle?

Taken from the latest stable Oracle production version 12.2: Data Types

The major difference is that VARCHAR2 is an internal data type and VARCHAR is an external data type. So we need to understand the difference between an internal and external data type...

Inside a database, values are stored in columns in tables. Internally, Oracle represents data in particular formats known as internal data types.

In general, OCI (Oracle Call Interface) applications do not work with internal data type representations of data, but with host language data types that are predefined by the language in which they are written. When data is transferred between an OCI client application and a database table, the OCI libraries convert the data between internal data types and external data types.

External types provide a convenience for the programmer by making it possible to work with host language types instead of proprietary data formats. OCI can perform a wide range of data type conversions when transferring data between an Oracle database and an OCI application. There are more OCI external data types than Oracle internal data types.

The VARCHAR2 data type is a variable-length string of characters with a maximum length of 4000 bytes. If the init.ora parameter max_string_size is default, the maximum length of a VARCHAR2 can be 4000 bytes. If the init.ora parameter max_string_size = extended, the maximum length of a VARCHAR2 can be 32767 bytes

The VARCHAR data type stores character strings of varying length. The first 2 bytes contain the length of the character string, and the remaining bytes contain the string. The specified length of the string in a bind or a define call must include the two length bytes, so the largest VARCHAR string that can be received or sent is 65533 bytes long, not 65535.

A quick test in a 12.2 database suggests that as an internal data type, Oracle still treats a VARCHAR as a pseudotype for VARCHAR2. It is NOT a SYNONYM which is an actual object type in Oracle.

SQL> select substr(banner,1,80) from v$version where rownum=1;
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production    

SQL> create table test (my_char varchar(20));
Table created.

SQL> desc test
Name                 Null?    Type
MY_CHAR                       VARCHAR2(20)

There are also some implications of VARCHAR for ProC/C++ Precompiler options. For programmers who are interested, the link is at: Pro*C/C++ Programmer's Guide

Clear all fields in a form upon going back with browser back button

This is what worked for me.

$(window).bind("pageshow", function() {
    $("#id").val('');
    $("#another_id").val('');
});

I initially had this in the $(document).ready section of my jquery, which also worked. However, I heard that not all browsers fire $(document).ready on hitting back button, so I took it out. I don't know the pros and cons of this approach, but I have tested on multiple browsers and on multiple devices, and no issues with this solution were found.

Facebook OAuth "The domain of this URL isn't included in the app's domain"

first step: use all https://example.in or ssl certificate URL , dont use http://example.in

second step: faceboook application setting->basic setting->add your domain or subdomain

third step: faceboook application login setting->Valid OAuth Redirect URIs->add your all redirect url after login

fourth step: faceboook application setting->advance setting->Domain Manager->add your domain name

do all this step then use your application id, application version ,app secret for setup

Java regex email

One another simple alternative to validate 99% of emails

public static final String EMAIL_VERIFICATION = "^([\\w-\\.]+){1,64}@([\\w&&[^_]]+){2,255}.[a-z]{2,}$";

How to add and remove classes in Javascript without jQuery

classList is available from IE10 onwards, use that if you can.

element.classList.add("something");
element.classList.remove("some-class");

How do I update a model value in JavaScript in a Razor view?

The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++)
{
    <br/>
    <b>Posted by :</b> @Model.Post[i].Username <br/>
    <span>@Model.Post[i].Content</span> <br/>
    if(Model.loginuser == Model.username)
    {
        @Html.HiddenFor(model => model.Post[i].PostID)
        @Html.TextAreaFor(model => model.addcomment.Content)
        <button type="submit">Add Comment</button>
    }
}

Copy output of a JavaScript variable to the clipboard

function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    // to avoid breaking orgain page when copying more words
    // cant copy when adding below this code
    // dummy.style.display = 'none'
    document.body.appendChild(dummy);
    //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')

Formatting a number with exactly two decimals in JavaScript

Number(((Math.random() * 100) + 1).toFixed(2))

this will return a random number from 1 to 100 rounded to 2 decimal places.

Get nth character of a string in Swift programming language

In Swift 5 without extension to the String :

var str = "ABCDEFGH"
for char in str {
if(char == "C") { }
}

Above Swift code as same as that Java code :

int n = 8;
var str = "ABCDEFGH"
for (int i=0; i<n; i++) {
if (str.charAt(i) == 'C') { }
}

How to make link not change color after visited?

Something like this should work:

a, a:visited { 
    color:red; text-decoration:none; 
    }

Find a string within a cell using VBA

I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.

Try this:

Option Explicit


Sub DoIHavePercentSymbol()
   Dim rng As Range

   Set rng = ActiveCell

   Do While rng.Value <> Empty
        If InStr(rng.Value, "%") = 0 Then
            MsgBox "I know nothing about percentages!"
            Set rng = rng.Offset(1)
            rng.Select
        Else
            MsgBox "I contain a % symbol!"
            Set rng = rng.Offset(1)
            rng.Select
        End If
   Loop

End Sub

InStr will return the number of times your search text appears in the string. I changed your if test to check for no matches first.

The message boxes and the .Selects are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.

Using an index to get an item, Python

You can use pop():

x=[2,3,4,5,6,7]
print(x.pop(2))

output is 4

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.

Make outer div be automatically the same height as its floating content

I know some people will hate me, but I've found display:table-cell to help in this cases.

It is really cleaner.

CMake: How to build external projects and include their targets

Edit: CMake now has builtin support for this. See new answer.

You can also force the build of the dependent target in a secondary make process

See my answer on a related topic.

How can I recursively find all files in current and subfolders based on wildcard matching?

Use find for that:

find . -name "foo*"

find needs a starting point, and the . (dot) points to the current directory.

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

I write it for information.

Delete the file in the project.

After Clean>Build>Proje Start

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

example:

>>> 10**1000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

You could even get, for example of a huge integer value, fib(4000000).

But still it does not (for now) supports an arbitrarily large float !!

If you need one big, large, float then check up on the decimal Module. There are examples of use on these foruns: OverflowError: (34, 'Result too large')

Another reference: http://docs.python.org/2/library/decimal.html

You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): Handling big numbers in code

Another reference: https://code.google.com/p/gmpy/

How to create a css rule for all elements except one class?

The negation pseudo-class seems to be what you are looking for.

table:not(.dojoxGrid) {color:red;}

It's not supported by = IE8 though.

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

How can I compare two time strings in the format HH:MM:SS?

Set the extracted part of the time to variables.

// If you don't have the second part then set it to 00.

 //Create date object and set the time to that
 var startTimeObject = new Date();
 startTimeObject.setHours(startHour, startMinute, startSecond);

 //Create date object and set the time to that
 var endTimeObject = new Date(startTimeObject);
 endTimeObject.setHours(endHour, endMinute, endSecond);

 //Now we are ready to compare both the dates
 if(startTimeObject > endTimeObject) {
     alert('End time should be after start time.');
 }
 else {
     alert('Entries are perfect.');
 }

Remove json element

For those of you who came here looking for how to remove an object from a JSON array based on object value:

_x000D_
_x000D_
let users = [{"name": "Ben"},{"name": "Tim"},{"name": "Harry"}];

 for (let [i, user] of users.entries()) {
    if (user.name == "Tim") {
        users.splice(i, 1);
    }
 }
_x000D_
_x000D_
_x000D_

User Tim is now removed from JSON array users.

Soft Edges using CSS?

It depends on what type of fading you are looking for.

But with shadow and rounded corners you can get a nice result. Rounded corners because the bigger the shadow, the weirder it will look in the edges unless you balance it out with rounded corners.

http://jsfiddle.net/tLu7u/

also.. http://css3pie.com/

How to redirect cin and cout to files?

Try this to redirect cout to file.

#include <iostream>
#include <fstream>

int main()
{
    /** backup cout buffer and redirect to out.txt **/
    std::ofstream out("out.txt");

    auto *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    std::cout << "This will be redirected to file out.txt" << std::endl;

    /** reset cout buffer **/
    std::cout.rdbuf(coutbuf);

    std::cout << "This will be printed on console" << std::endl;

    return 0;
}

Read full article Use std::rdbuf to Redirect cin and cout

How to check if dropdown is disabled?

Try following or check demo disabled and readonly

$('#dropUnit').is(':disabled') //Returns bool
$('#dropUnit').attr('readonly') == "readonly"  //If Condition

You can check jQuery FAQ .

Is there a short cut for going back to the beginning of a file by vi editor?

using :<line number> you can navigate to any line, thus :1 takes you to the first line.

How to consume a webApi from asp.net Web API to store result in database?

For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:

HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects");
if (response.IsSuccessStatusCode)
{
    var data = await response.Content.ReadAsStringAsync();
    var product = JsonConvert.DeserializeObject<Product>(data);
}

This way my content is parsed into a JSON string and then I convert it to my object.

Trim specific character from a string

I would suggest looking at lodash and how they implemented the trim function.

See Lodash Trim for the documentation and the source to see the exact code that does the trimming.

I know this does not provide an exact answer your question, but I think it's good to set a reference to a library on such a question since others might find it useful.

SQL Server find and replace specific word in all rows of specific column

You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.

RuntimeWarning: DateTimeField received a naive datetime

In the model, do not pass the value:

timezone.now()

Rather, remove the parenthesis, and pass:

timezone.now

If you continue to get a runtime error warning, consider changing the model field from DateTimeField to DateField.

Cannot invoke an expression whose type lacks a call signature

As mentioned in the github issue originally linked by @peter in the comments:

const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);

Simple java program of pyramid

This code will print a pyramid of dollars.

public static void main(String[] args) {

     for(int i=0;i<5;i++) {
         for(int j=0;j<5-i;j++) {
             System.out.print(" ");
         }
        for(int k=0;k<=i;k++) {
            System.out.print("$ ");
        }
        System.out.println();  
    }

}

OUPUT :

     $ 
    $ $ 
   $ $ $ 
  $ $ $ $ 
 $ $ $ $ $

$(this).val() not working to get text from span using jquery

Instead of .val() use .text(), like this:

$(".ui-datepicker-month").live("click", function () {
    var monthname =  $(this).text();
    alert(monthname);
});

Or in jQuery 1.7+ use on() as live is deprecated:

$(document).on('click', '.ui-datepicker-month', function () {
    var monthname =  $(this).text();
    alert(monthname);
});

.val() is for input type elements (including textareas and dropdowns), since you're dealing with an element with text content, use .text() here.

Bower: ENOGIT Git is not installed or not in the PATH

Adding Git to Windows 7/8/8.1 Path

Note: You must have msysgit installed on your machine. Also, the path to my Git installation is "C:\Program Files (x86)\Git". Yours might be different. Please check where yours is before continuing.

Open the Windows Environment Variables/Path Window.

  1. Right-click on My Computer -> Properties
  2. Click Advanced System Settings link from the left side column
  3. Click Environment Variables in the bottom of the window
  4. Then under System Variables look for the path variable and click edit
  5. Add the pwd to Git's binary and cmd at the end of the string like this:

    ;%PROGRAMFILES(x86)%\Git\bin;%PROGRAMFILES(x86)%\Git\cmd
    

Now test it out in PowerShell. Type git and see if it recognizes the command.

This is image showing you how to do so!

Source: Adding Git to Windows 7 Path

How to add text inside the doughnut chart using Chart.js?

You have to modify the code like: in chart.Doughnut.defaults

labelFontFamily : "Arial",
labelFontStyle : "normal",
labelFontSize : 24,
labelFontColor : "#666"

and then in function drawPieSegments

ctx.fillText(data[0].value + "%", width/2 - 20, width/2, 200);

See this pull: https://github.com/nnnick/Chart.js/pull/35

here is a fiddle http://jsfiddle.net/mayankcpdixit/6xV78/ implementing the same.

Convert integers to strings to create output filenames at run time

I've tried @Alejandro and @user2361779 already but it gives me an unsatisfied result such as file 1.txt or file1 .txt instead of file1.txt. However i find the better solution:

...
integer :: i
character(len=5) :: char_i     ! use your maximum expected len
character(len=32) :: filename

write(char_i, '(I5)') i        ! convert integer to char
write(filename, '("path/to/file/", A, ".dat")') trim(adjustl(char_i))
...

Explanation:

e.g. set i = 10 and write(char_i, '(I5)') i

char_i                gives  "   10" ! this is original value of char_i

adjustl(char_i)       gives  "10   " ! adjust char_i to the left

trim(adjustl(char_i)) gives  "10"    ! adjust char_i to the left then remove blank space on the right

I think this is a simplest solution that give you a dynamical length filename without any legacy blank spaces from integer to string conversion process.

AngularJS : When to use service instead of factory

Explanation

You got different things here:

First:

  • If you use a service you will get the instance of a function ("this" keyword).
  • If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory).

ref: angular.service vs angular.factory

Second:

Keep in mind all providers in AngularJS (value, constant, services, factories) are singletons!

Third:

Using one or the other (service or factory) is about code style. But, the common way in AngularJS is to use factory.

Why ?

Because "The factory method is the most common way of getting objects into AngularJS dependency injection system. It is very flexible and can contain sophisticated creation logic. Since factories are regular functions, we can also take advantage of a new lexical scope to simulate "private" variables. This is very useful as we can hide implementation details of a given service."

(ref: http://www.amazon.com/Mastering-Web-Application-Development-AngularJS/dp/1782161821).


Usage

Service : Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with injectedArg.call(this) or similar.

Factory : Could be useful for returning a ‘class’ function that can then be new`ed to create instances.

So, use a factory when you have complex logic in your service and you don't want expose this complexity.

In other cases if you want to return an instance of a service just use service.

But you'll see with time that you'll use factory in 80% of cases I think.

For more details: http://blog.manishchhabra.com/2013/09/angularjs-service-vs-factory-with-example/


UPDATE :

Excellent post here : http://iffycan.blogspot.com.ar/2013/05/angular-service-or-factory.html

"If you want your function to be called like a normal function, use factory. If you want your function to be instantiated with the new operator, use service. If you don't know the difference, use factory."


UPDATE :

AngularJS team does his work and give an explanation: http://docs.angularjs.org/guide/providers

And from this page :

"Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions."

Remove HTML Tags from an NSString on the iPhone

Take a look at NSXMLParser. It's a SAX-style parser. You should be able to use it to detect tags or other unwanted elements in the XML document and ignore them, capturing only pure text.

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

Whenever I set debug="off" in my web.config and run my mvc4 application i would end up with ...

<script src="/bundles/jquery?v=<some long string>"></script>

in my html code and a JavaScript error

Expected ';'

There were 2 ways to get rid of the javascript error

  1. set BundleTable.EnableOptimizations = false in BundleConfig.cs

OR

  1. I ended up using NuGet Package Manager to update WebGrease.dll. It works fine irrespective if debug= "true" or debug = "false".

regex error - nothing to repeat

regular expression normally uses * and + in theory of language. I encounter the same bug while executing the line code

re.split("*",text)

to solve it, it needs to include \ before * and +

re.split("\*",text)

Return content with IHttpActionResult for non-OK response

I ended up going with the following solution:

public class HttpActionResult : IHttpActionResult
{
    private readonly string _message;
    private readonly HttpStatusCode _statusCode;

    public HttpActionResult(HttpStatusCode statusCode, string message)
    {
        _statusCode = statusCode;
        _message = message;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = new HttpResponseMessage(_statusCode)
        {
            Content = new StringContent(_message)
        };
        return Task.FromResult(response);
    }
}

... which can be used like this:

public IHttpActionResult Get()
{
   return new HttpActionResult(HttpStatusCode.InternalServerError, "error message"); // can use any HTTP status code
}

I'm open to suggestions for improvement. :)

Remove excess whitespace from within a string

$str = "I      am a PHP   Developer";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
   if (isset($str_arr[$i + 1])  && $str_arr[$i] == ' ' && $str_arr[$i] == $str_arr[$i + 1]) {
       unset($str_arr[$i]);
   } 
   else {
     continue;
   }
}
echo implode("", $str_arr);

ImportError: No module named pip

I had a similar problem with virtualenv that had python3.8 while installing dependencies from requirements.txt file. I managed to get it to work by activating the virtualenv and then running the command python -m pip install -r requirements.txt and it worked.

How do I mock a REST template exchange?

This is an example with the non deprecated ArgumentMatchers class

when(restTemplate.exchange(
                ArgumentMatchers.anyString(),
                ArgumentMatchers.any(HttpMethod.class),
                ArgumentMatchers.any(),
                ArgumentMatchers.<Class<String>>any()))
             .thenReturn(responseEntity);

How to delete the first row of a dataframe in R?

No one probably really wants to remove row one. So if you are looking for something meaningful, that is conditional selection

#remove rows that have long length and "0" value for vector E

>> setNew<-set[!(set$length=="long" & set$E==0),]

How can I select rows with most recent timestamp for each key value?

You can join the table with itself (on sensor id), and add left.timestamp < right.timestamp as join condition. Then you pick the rows, where right.id is null. Voila, you got the latest entry per sensor.

http://sqlfiddle.com/#!9/45147/37

SELECT L.* FROM sensorTable L
LEFT JOIN sensorTable R ON
L.sensorID = R.sensorID AND
L.timestamp < R.timestamp
WHERE isnull (R.sensorID)

But please note, that this will be very resource intensive if you have a little amount of ids and many values! So, I wouldn't recommend this for some sort of Measuring-Stuff, where each Sensor collects a value every minute. However in a Use-Case, where you need to track "Revisions" of something that changes just "sometimes", it's easy going.

You must add a reference to assembly 'netstandard, Version=2.0.0.0

We started getting this error on the production server after deploying the application migrated from 4.6.1 to 4.7.2.

We noticed that the .NET framework 4.7.2 was not installed there. In order to solve this issue we did the following steps:

  1. Installed the .NET Framework 4.7.2 from:

    https://support.microsoft.com/en-us/help/4054530/microsoft-net-framework-4-7-2-offline-installer-for-windows

  2. Restarted the machine

  3. Confirmed the .NET Framework version with the help of How do I find the .NET version?

Running the application again with the .Net Framework 4.7.2 version installed on the machine fixed the issue.

Set the space between Elements in Row Flutter

I believe the original post was about removing the space between the buttons in a row, not adding space.

The trick is that the minimum space between the buttons was due to padding built into the buttons as part of the material design specification.

So, don't use buttons! But a GestureDetector instead. This widget type give the onClick / onTap functionality but without the styling.

See this post for an example.

https://stackoverflow.com/a/56001817/766115

How to list AD group membership for AD users using input list?

First: As it currently stands, the $User variable does not have a .Users property. In your code, $User simply represents one line (the "current" line in the foreach loop) from the text file.

$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof

Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:

  1. Query forest for list of domains
  2. Call Get-ADUser for each domain (you may have to specify alternate credentials via the -Credential parameter

Thirdly, to get a list of groups that a user is a member of:

$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';

# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins

Fourthly: To get the final, desired string format, simply add the $User.Name, a semicolon, and the $GroupMembership string together:

$User.SamAccountName + ';' + $GroupMembership;

Converting an object to a string

None of the solutions here worked for me. JSON.stringify seems to be what a lot of people say, but it cuts out functions and seems pretty broken for some objects and arrays I tried when testing it.

I made my own solution which works in Chrome at least. Posting it here so anyone that looks this up on Google can find it.

//Make an object a string that evaluates to an equivalent object
//  Note that eval() seems tricky and sometimes you have to do
//  something like eval("a = " + yourString), then use the value
//  of a.
//
//  Also this leaves extra commas after everything, but JavaScript
//  ignores them.
function convertToText(obj) {
    //create an array that will later be joined into a string.
    var string = [];

    //is object
    //    Both arrays and objects seem to return "object"
    //    when typeof(obj) is applied to them. So instead
    //    I am checking to see if they have the property
    //    join, which normal objects don't have but
    //    arrays do.
    if (typeof(obj) == "object" && (obj.join == undefined)) {
        string.push("{");
        for (prop in obj) {
            string.push(prop, ": ", convertToText(obj[prop]), ",");
        };
        string.push("}");

    //is array
    } else if (typeof(obj) == "object" && !(obj.join == undefined)) {
        string.push("[")
        for(prop in obj) {
            string.push(convertToText(obj[prop]), ",");
        }
        string.push("]")

    //is function
    } else if (typeof(obj) == "function") {
        string.push(obj.toString())

    //all other values can be done with JSON.stringify
    } else {
        string.push(JSON.stringify(obj))
    }

    return string.join("")
}

EDIT: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement here with the comment:

Here is a little bit changed code, which can handle 'null' and 'undefined', and also do not add excessive commas.

Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.

Check if string begins with something?

A little more reusable function:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

How set background drawable programmatically in Android

You can also set the background of any Image:

View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);

UDP vs TCP, how much faster is it?

Keep in mind that TCP usually keeps multiple messages on wire. If you want to implement this in UDP you'll have quite a lot of work if you want to do it reliably. Your solution is either going to be less reliable, less fast or an incredible amount of work. There are valid applications of UDP, but if you're asking this question yours probably is not.

How to display a range input slider vertically

You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:

_x000D_
_x000D_
input[type="range"] {_x000D_
   position: absolute;_x000D_
   top: 40%;_x000D_
   transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
_x000D_
_x000D_


or the 3d transform equivalent:

input[type="range"] {
   transform: rotateZ(270deg);
}

You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.

Why is super.super.method(); not allowed in Java?

I think if you overwrite a method and want to all the super-class version of it (like, say for equals), then you virtually always want to call the direct superclass version first, which one will call its superclass version in turn if it wants.

I think it only makes rarely sense (if at all. i can't think of a case where it does) to call some arbitrary superclass' version of a method. I don't know if that is possible at all in Java. It can be done in C++:

this->ReallyTheBase::foo();

Android XML Percent Symbol

To allow the app using formatted strings from resources you should correct your xml. So, for example

<string name="app_name">Your App name, ver.%d</string>

should be replaced with

<string name="app_name">Your App name, ver.%1$d</string>

You can see this for details.

Order of items in classes: Fields, Properties, Constructors, Methods

My preference is to order by kind and then be decreasing visibility as follows

public methods
public events
public properties

protected methods
protected events
protected properties

private methods
private events
private properties
private fields

public delegates
public interfaces
public classes
public structs

protected delegates
protected interfaces
protected classes
protected structs

private delegates
private interfaces
private classes
private structs

I know this violates Style Cop and if someone can give me a good reason why I should place the implementation details of a type before its interface I am willing to change. At present, I have a strong preference for putting private members last.

Note: I don't use public or protected fields.

How to obtain values of request variables using Python and Flask

You can get posted form data from request.form and query string data from request.args.

myvar =  request.form["myvar"]
myvar = request.args["myvar"]

How to read data from java properties file using Spring Boot

You can use @PropertySource to externalize your configuration to a properties file. There is number of way to do get properties:

1. Assign the property values to fields by using @Value with PropertySourcesPlaceholderConfigurer to resolve ${} in @Value:

@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Value("${gMapReportUrl}")
    private String gMapReportUrl;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

2. Get the property values by using Environment:

@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Autowired
    private Environment env;

    public void foo() {
        env.getProperty("gMapReportUrl");
    }

}

Hope this can help

Writing new lines to a text file in PowerShell

It's also possible to assign newline and carriage return to variables and then append them to texts inside PowerShell scripts:

$OFS = "`r`n"
$msg = "This is First Line" + $OFS + "This is Second Line" + $OFS
Write-Host $msg

What does PHP keyword 'var' do?

The var keyword is used to declare variables in a class in PHP 4:

class Foo {
    var $bar;
}

With PHP 5 property and method visibility (public, protected and private) was introduced and thus var is deprecated.

Java URL encoding of query string parameters

In my case i just needed to pass the whole url and encode only the value of each parameters. I didn't find a common code to do that so (!!) so i created this small method to do the job :

public static String encodeUrl(String url) throws Exception {
    if (url == null || !url.contains("?")) {
        return url;
    }

    List<String> list = new ArrayList<>();
    String rootUrl = url.split("\\?")[0] + "?";
    String paramsUrl = url.replace(rootUrl, "");
    List<String> paramsUrlList = Arrays.asList(paramsUrl.split("&"));
    for (String param : paramsUrlList) {
        if (param.contains("=")) {
            String key = param.split("=")[0];
            String value = param.replace(key + "=", "");
            list.add(key + "=" +  URLEncoder.encode(value, "UTF-8"));
        }
        else {
            list.add(param);
        }
    }

    return rootUrl + StringUtils.join(list, "&");
}

public static String decodeUrl(String url) throws Exception {
    return URLDecoder.decode(url, "UTF-8");
}

It uses org.apache.commons.lang3.StringUtils

Create table variable in MySQL

They don't exist in MySQL do they? Just use a temp table:

CREATE PROCEDURE my_proc () BEGIN 

CREATE TEMPORARY TABLE TempTable (myid int, myfield varchar(100)); 
INSERT INTO TempTable SELECT tblid, tblfield FROM Table1; 

/* Do some more stuff .... */

From MySQL here

"You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed. This means that two different connections can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.)"

Image resolution for new iPhone 6 and 6+, @3x support added?

I've tried in a sample project to use standard, @2x and @3x images, and the iPhone 6+ simulator uses the @3x image. So it would seem that there are @3x images to be done (if the simulator actually replicates the device's behavior). But the strange thing is that all devices (simulators) seem to use this @3x image when it's on the project structure, iPhone 4S/iPhone 5 too.
The lack of communication from Apple on a potential @3x structure, while they ask developers to publish their iOS8 apps is quite confusing, especially when seeing those results on simulator.

**Edit from Apple's Website **: Also found this on the "What's new on iOS 8" section on Apple's developer space :

Support for a New Screen Scale The iPhone 6 Plus uses a new Retina HD display with a screen scale of 3.0. To provide the best possible experience on these devices, include new artwork designed for this screen scale. In Xcode 6, asset catalogs can include images at 1x, 2x, and 3x sizes; simply add the new image assets and iOS will choose the correct assets when running on an iPhone 6 Plus. The image loading behavior in iOS also recognizes an @3x suffix.

Still not understanding why all devices seem to load the @3x. Maybe it's because I'm using regular files and not xcassets ? Will try soon.

Edit after further testing : Ok it seems that iOS8 has a talk in this. When testing on an iOS 7.1 iPhone 5 simulator, it uses correctly the @2x image. But when launching the same on iOS 8 it uses the @3x on iPhone 5. Not sure if that's a wanted behavior or a mistake/bug in iOS8 GM or simulators in Xcode 6 though.

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

This happened to me on VS2013(Update 5)/ASP.NET 4.5, under project type "Web Application" that includes MVC and Web API 2. Error happened right after creating the project and before adding any code. Adding the following configuration fix it for me. After resolving "System.Web.Helpers" issue two more similar errors surfaced for "System.Web.Mvc" and "System.Web.WebPages".

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Excel VBA - Range.Copy transpose paste

WorksheetFunction Transpose()

Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula

    =TRANSPOSE(Sheet1!A1:A5)

or if you prefer VBA:

    Dim v
    v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
    Sheet2.Range("A1").Resize(1, UBound(v)) = v

Note: alternatively you could use late-bound Application.Transpose instead.

MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.

Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365

jQuery: go to URL with target="_blank"

Try using the following code.

$(document).ready(function(){
    $("a[@href^='http']").attr('target','_blank');
});

Return the characters after Nth character in a string

If your numbers are always 4 digits long:

=RIGHT(A1,LEN(A1)-5) //'0001 Baseball' returns Baseball

If the numbers are variable (i.e. could be more or less than 4 digits) then:

=RIGHT(A1,LEN(A1)-FIND(" ",A1,1)) //'123456 Baseball’ returns Baseball

Difference between Git and GitHub

There are a number of obvious differences between Git and GitHub.

Git itself is really focused on the essential tasks of version control. It maintains a commit history, it allows you to reverse changes through reset and revert commands, and it allows you to share code with other developers through push and pull commands. I think those are the essential features every developer wants from a DVCS tool.

Git versus GitHub Comparison Chart

No Scope Creep with Git

But one thing about Git is that it is really just laser focused on source code control and nothing else. That's awesome, but it also means the tool lacks many features organizations want. For example, there is no built-in user management facilities to authenticate who is connecting and committing code. Integration with things like Jira or Jenkins are left up to developers to figure out through things like hooks. Basically, there are a load of places where features could be integrated. That's where organizations like GitHub and GitLab come in.

Additional GitHub Features

GitHub's primary 'value-add' is that it provides a cloud based platform for Git. That in itself is awesome. On top of that, GitHub also offers:

  • simple task tracking
  • a GitHub desktop app
  • online file editing
  • branch protection rules
  • pull request features
  • organizational tools
  • interaction limits for hotheads
  • emoji support!!! :octocat: :+1:

So GitHub really adds polish and refinement to an already popular DVCS tool.

Git and GitHub competitors

Sometimes when it comes to differentiating between Git and GitHub, I think it's good to look at who they compete against. Git competes on a plane with tools like Mercurial, Subversion and RTC, whereas GitHub is more in the SaaS space competing against cloud vendors such as GitLab and Atlassian's BitBucket.

No GitHub Required

One thing I always like to remind people of is that you don't need GitHub or GitLab or BitBucket to use Git. Git was released in what, 2005? GitHub didn't come on the scene until 2007 or 2008, so big organizations were doing distributed version control with Git long before the cloud hosting vendors came along. So Git is just fine on its own. It doesn't need a cloud hosting service to be effective. But at the same time, having a PaaS provider certainly doesn't hurt.

Working with GitHub Desktop

By the way, you mentioned the mismatch between the repositories in your GitHub account and the repos you have locally? That's understandable. Until you've connected and done a pull or a fetch, the local Git repo doesn't know about the remote GitHub repo. Having said that, GitHub provides a tool known as the GitHub desktop that allows you to connect to GitHub from a desktop client and easily load local Git repos to GitHub, or bring GitHub repos onto your local machine.

GitHub Desktop

I'm not overly impressed by the tool, as once you know Git, these things aren't that hard to do in the Bash shell, but it's an option.

The fight between Git and GitHub

How do I format a number with commas in T-SQL?

Tried the money trick above, and this works great for numerical values with two or less significant digits. I created my own function to format numbers with decimals:

CREATE FUNCTION [dbo].[fn_FormatWithCommas] 
(
    -- Add the parameters for the function here
    @value varchar(50)
)
RETURNS varchar(50)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @WholeNumber varchar(50) = NULL, @Decimal varchar(10) = '', @CharIndex int = charindex('.', @value)

    IF (@CharIndex > 0)
        SELECT @WholeNumber = SUBSTRING(@value, 1, @CharIndex-1), @Decimal = SUBSTRING(@value, @CharIndex, LEN(@value))
    ELSE
        SET @WholeNumber = @value

    IF(LEN(@WholeNumber) > 3)
        SET @WholeNumber = dbo.fn_FormatWithCommas(SUBSTRING(@WholeNumber, 1, LEN(@WholeNumber)-3)) + ',' + RIGHT(@WholeNumber, 3)



    -- Return the result of the function
    RETURN @WholeNumber + @Decimal

END

"UnboundLocalError: local variable referenced before assignment" after an if statement

Before I start, I'd like to note that I can't actually test this since your script reads data from a file that I don't have.

'T' is defined in a local scope for the declared function. In the first instance 'T' is assigned the value of 'data[2]' because the conditional statement above apparently evaluates to True. Since the second call to the function causes the 'UnboundLocalError' exception to occur, the local variable 'T' is getting set and the conditional assignment is never getting triggered.

Since you appear to want to return the first bit of data in the file that matches your conditonal statement, you might want to modify you function to look like this:

def temp_sky(lreq, breq):
    for line in tfile:
        data = line.split()
        if ( abs(float(data[0]) - lreq) <= 0.1 and abs(float(data[1]) - breq) <= 0.1):            
            return data[2]
    return None

That way the desired value gets returned when it is found, and 'None' is returned when no matching data is found.

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

Try without command mvn in the command line. Example:

From:

mvn clean install jetty:run

To:

clean install jetty:run

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

The line you found just looks for the environmental variable PORT, if it's defined it uses it, otherwise uses the default port 3000. You have to define this environmental variable first (no need to be root)

export PORT=8080
node <your-app.js>

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Using = causes the variable to be assigned a value. If the variable already had a value, it is replaced. This value will be expanded when it is used. For example:

HELLO = world
HELLO_WORLD = $(HELLO) world!

# This echoes "world world!"
echo $(HELLO_WORLD)

HELLO = hello

# This echoes "hello world!"
echo $(HELLO_WORLD)

Using := is similar to using =. However, instead of the value being expanded when it is used, it is expanded during the assignment. For example:

HELLO = world
HELLO_WORLD := $(HELLO) world!

# This echoes "world world!"
echo $(HELLO_WORLD)

HELLO = hello

# Still echoes "world world!"
echo $(HELLO_WORLD)

HELLO_WORLD := $(HELLO) world!

# This echoes "hello world!"
echo $(HELLO_WORLD)

Using ?= assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value (VAR=), it is still considered set I think. Otherwise, functions exactly like =.

Using += is like using =, but instead of replacing the value, the value is appended to the current one, with a space in between. If the variable was previously set with :=, it is expanded I think. The resulting value is expanded when it is used I think. For example:

HELLO_WORLD = hello
HELLO_WORLD += world!

# This echoes "hello world!"
echo $(HELLO_WORLD)

If something like HELLO_WORLD = $(HELLO_WORLD) world! were used, recursion would result, which would most likely end the execution of your Makefile. If A := $(A) $(B) were used, the result would not be the exact same as using += because B is expanded with := whereas += would not cause B to be expanded.

jQuery: Can I call delay() between addClass() and such?

Of course it would be more simple if you extend jQuery like this:

$.fn.addClassDelay = function(className,delay) {
    var $addClassDelayElement = $(this), $addClassName = className;
    $addClassDelayElement.addClass($addClassName);
    setTimeout(function(){
        $addClassDelayElement.removeClass($addClassName);
    },delay);
};

after that you can use this function like addClass:

$('div').addClassDelay('clicked',1000);

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Note: For MySQL 5.7+ please see answer from @Lahiru to this question. That contains more current information.

For MySQL < 5.7:

The default root password is blank (i.e. empty string) not root. So you can just login as:

mysql -u root

You should obviously change your root password after installation

mysqladmin -u root password [newpassword]

In most cases you should also set up individual user accounts before working extensively with the DB as well.

Access Enum value using EL with JSTL

I generally consider it bad practice to mix java code into jsps/tag files. Using 'eq' should do the trick :

<c:if test="${dp.Status eq 'OLD'}">
  ...
</c:if>

How to set the height of table header in UITableView?

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
}

or you can use like this also

tableView.estimatedSectionHeaderHeight 

How to delete multiple pandas (python) dataframes from memory to save RAM?

In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).

You can manually trigger the garbage collection using

import gc
gc.collect()

But frequent calls to garbage collection is discouraged as it is a costly operation and may affect performance.

Reference

How does Python manage int and long?

On my machine:

>>> print type(1<<30)
<type 'int'>
>>> print type(1<<31)
<type 'long'>
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'long'>

Python uses ints (32 bit signed integers, I don't know if they are C ints under the hood or not) for values that fit into 32 bit, but automatically switches to longs (arbitrarily large number of bits - i.e. bignums) for anything larger. I'm guessing this speeds things up for smaller values while avoiding any overflows with a seamless transition to bignums.

How do I truly reset every setting in Visual Studio 2012?

1) Run Visual Studio Installer

2) Click More on your Installed version and select Repair

3) Restart

Worked on Visual Studio 2017 Community

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

Closure in Java 7

A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.

Since Java 1.1, anonymous inner class have provided this facility in a highly verbose manner. They also have a restriction of only being able to use final (and definitely assigned) local variables. (Note, even non-final local variables are in scope, but cannot be used.)

Java SE 8 is intended to have a more concise version of this for single-method interfaces*, called "lambdas". Lambdas have much the same restrictions as anonymous inner classes, although some details vary randomly.

Lambdas are being developed under Project Lambda and JSR 335.

*Originally the design was more flexible allowing Single Abstract Methods (SAM) types. Unfortunately the new design is less flexible, but does attempt to justify allowing implementation within interfaces.

How do I get Fiddler to stop ignoring traffic to localhost?

To get Fiddler to capture traffic when you are debugging on local host, after you hit F5 to begin degugging change the address so that localhost has a "." after it.

For instance, you start debugging and the you have the following URL in the Address bar:

http://localhost:49573/Default.aspx

Change it to:

http://localhost.:49573/Default.aspx

Hit enter and Fidder will start picking up your traffic.

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

I had the same problem, what i found was that Android Developer tools doesn't work well with JDK 8. I deleted my current JDK 8 and and installed JDK 7 and worked just like that no increase of heap memory or delete of .gradle folder.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

How do I remove a specific element from a JSONArray?

public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {

JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){     
    if(i!=pos)
        Njarray.put(jarray.get(i));     
}
}catch (Exception e){e.printStackTrace();}
return Njarray;

}

Android getting value from selected radiobutton

int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();

Hope this works. You can convert your output to string in the above manner. gender.getCheckedRadioButtonId(); - gender is the id of RadioGroup.

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

How can I plot with 2 different y-axes?

One option is to make two plots side by side. ggplot2 provides a nice option for this with facet_wrap():

dat <- data.frame(x = c(rnorm(100), rnorm(100, 10, 2))
  , y = c(rnorm(100), rlnorm(100, 9, 2))
  , index = rep(1:2, each = 100)
  )

require(ggplot2)
ggplot(dat, aes(x,y)) + 
geom_point() + 
facet_wrap(~ index, scales = "free_y")

How to install JSON.NET using NuGet?

I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..

enter image description here

WCF Service, the type provided as the service attribute values…could not be found

  1. When you create an IIS application only the /bin or /App_Code folder is in the root directory of the IIS app. So just remember put all the code in the root /bin or /App_code directory (see http://blogs.msdn.com/b/chrsmith/archive/2006/08/10/wcf-service-nesting-in-iis.aspx).

  2. Make sure that the service name and the contract contain full name(e.g namespace.ClassName), and the service name and interface is the same as the name attribute of the service tag and contract of endpoint in web.config.

How to programmatically close a JFrame

You have to insert the call into the AWT message queue so all the timing happens correctly, otherwise it will not dispatch the correct event sequence, especially in a multi-threaded program. When this is done you may handle the resulting event sequence exactly as you would if the user has clicked on the [x] button for an OS suppled decorated JFrame.

public void closeWindow()
{
    if(awtWindow_ != null) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                awtWindow_.dispatchEvent(new WindowEvent(awtWindow_, WindowEvent.WINDOW_CLOSING));
            }
        });
    }
}

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

You can add function to:

c:\Users\David\Documents\WindowsPowerShell\profile.ps1

An the function will be available.

How to check if a string contains a substring in Bash

How about this:

text="   <tag>bmnmn</tag>  "
if [[ "$text" =~ "<tag>" ]]; then
   echo "matched"
else
   echo "not matched"
fi

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

I made the following filter:

angular.module('app').filter('ifEmpty', function() {
    return function(input, defaultValue) {
        if (angular.isUndefined(input) || input === null || input === '') {
            return defaultValue;
        }

        return input;
    }
});

To be used like this:

<span>{{aPrice | currency | ifEmpty:'N/A'}}</span>
<span>{{aNum | number:3 | ifEmpty:0}}</span>

Multiple radio button groups in one form

This is very simple you need to keep different names of every radio input group.

_x000D_
_x000D_
      <input type="radio" name="price">Thousand<br>_x000D_
      <input type="radio" name="price">Lakh<br>_x000D_
      <input type="radio" name="price">Crore_x000D_
      _x000D_
      </br><hr>_x000D_
_x000D_
      <input type="radio" name="gender">Male<br>_x000D_
      <input type="radio" name="gender">Female<br>_x000D_
      <input type="radio" name="gender">Other
_x000D_
_x000D_
_x000D_

Ajax Upload image

first in your ajax call include success & error function and then check if it gives you error or what?

your code should be like this

$(document).ready(function (e) {
    $('#imageUploadForm').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

    $("#ImageBrowse").on("change", function() {
        $("#imageUploadForm").submit();
    });
});

css - position div to bottom of containing div

Add position: relative to .outside. (https://developer.mozilla.org/en-US/docs/CSS/position)

Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.

The "initial container" would be <body>, but adding the above makes .outside positioned.

Deep copy vs Shallow Copy

The quintessential example of this is an array of pointers to structs or objects (that are mutable).

A shallow copy copies the array and maintains references to the original objects.

A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.

The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors and destructors.

The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.

Namespace for [DataContract]

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx

DataContractAttribute is in System.Runtime.Serialization namespace and you should reference System.Runtime.Serialization.dll. It's only available in .Net >= 3

Concatenating Files And Insert New Line In Between Files

In python, this concatenates with blank lines between files (the , suppresses adding an extra trailing blank line):

print '\n'.join(open(f).read() for f in filenames),

Here is the ugly python one-liner that can be called from the shell and prints the output to a file:

python -c "from sys import argv; print '\n'.join(open(f).read() for f in argv[1:])," File*.txt > finalfile.txt

How can I remove a style added with .css() function?

How about something like:

var myCss = $(element).attr('css');
myCss = myCss.replace('background-color: '+$(element).css('background-color')+';', '');
if(myCss == '') {
  $(element).removeAttr('css');
} else {
  $(element).attr('css', myCss);
}

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

Use Pre-request script tab to write javascript to get and save the date into a variable:

const dateNow= new Date();
pm.environment.set('currentDate', dateNow.toISOString());

and then use it in the request body as follows:

"currentDate": "{{currentDate}}"

npm install Error: rollbackFailedOptional

In my case I had to edit the .npmrc directly and add the proxy settings manually.

proxy=http://yourorganizationproxy.com:8080
https-proxy=http://yourorganizationproxy.com:8080

Hope this helps someone.

How to detect the swipe left or Right in Android?

here is generic swipe left detector for any view in kotlin using databinding

@BindingAdapter("onSwipeLeft")
fun View.setOnSwipeLeft(runnable: Runnable) {
    setOnTouchListener(object : View.OnTouchListener {
        var x0 = 0F; var y0 = 0F; var t0 = 0L
        val defaultClickDuration = 200

        override fun onTouch(v: View?, motionEvent: MotionEvent?): Boolean {
            motionEvent?.let { event ->
                when(event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        x0 = event.x; y0 = event.y; t0 = System.currentTimeMillis()
                    }
                    MotionEvent.ACTION_UP -> {
                        val x1 = event.x; val y1 = event.y; val t1 = System.currentTimeMillis()

                        if (x0 == x1 && y0 == y1 && (t1 - t0) < defaultClickDuration) {
                            performClick()
                            return false
                        }
                        if (x0 > x1) { runnable.run() }
                    }
                    else -> {}
                }
            }
            return true
        }
    })
}

and then to use it in your layout:

app:onSwipeLeft="@{() -> viewModel.swipeLeftHandler()}"

Get URL query string parameters

Also if you are looking for current file name along with the query string, you will just need following

basename($_SERVER['REQUEST_URI'])

It would provide you info like following example

file.php?arg1=val&arg2=val

And if you also want full path of file as well starting from root, e.g. /folder/folder2/file.php?arg1=val&arg2=val then just remove basename() function and just use fillowing

$_SERVER['REQUEST_URI']

Convert datatable to JSON in C#

I have simple function to convert datatable to json string.

I have used Newtonsoft to generate string. I don't use Newtonsoft to totaly serialize Datatable. Be careful about this.

Maybe this can be useful.

 private string DataTableToJson(DataTable dt) {
  if (dt == null) {
   return "[]";
  };
  if (dt.Rows.Count < 1) {
   return "[]";
  };

  JArray array = new JArray();
  foreach(DataRow dr in dt.Rows) {
   JObject item = new JObject();
   foreach(DataColumn col in dt.Columns) {
    item.Add(col.ColumnName, dr[col.ColumnName]?.ToString());
   }
   array.Add(item);
  }

  return array.ToString(Newtonsoft.Json.Formatting.Indented);
 }

How to set timeout in Retrofit library?

I am using Retrofit 1.9 to obtain a XML.

public class ServicioConexionRetrofitXML {

    public static final String API_BASE_URL = new GestorPreferencias().getPreferencias().getHost();
    public static final long tiempoMaximoRespuestaSegundos = 60;
    public static final long tiempoMaximoLecturaSegundos = 100;
    public static final OkHttpClient clienteOkHttp = new OkHttpClient();


    private static RestAdapter.Builder builder = new RestAdapter.Builder().
            setEndpoint(API_BASE_URL).
            setClient(new OkClient(clienteOkHttp)).setConverter(new SimpleXMLConverter());


    public static <S> S createService(Class<S> serviceClass) {
        clienteOkHttp.setConnectTimeout(tiempoMaximoRespuestaSegundos, TimeUnit.SECONDS);
        clienteOkHttp.setReadTimeout(tiempoMaximoLecturaSegundos, TimeUnit.SECONDS);
        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass);
    }

}

If you are using Retrofit 1.9.0 and okhttp 2.6.0, add to your Gradle file.

    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.6.0'
    // Librería de retrofit para XML converter (Simple) Se excluyen grupos para que no entre
    // en conflicto.
    compile('com.squareup.retrofit:converter-simplexml:1.9.0') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
    }

Note: If you need to fetch a JSON, just remove from code above.

.setConverter(new SimpleXMLConverter())

if variable contains

You might want indexOf

if (code.indexOf("ST1") >= 0) { ... }
else if (code.indexOf("ST2") >= 0) { ... }

It checks if contains is anywhere in the string variable code. This requires code to be a string. If you want this solution to be case-insensitive you have to change the case to all the same with either String.toLowerCase() or String.toUpperCase().

You could also work with a switch statement like

switch (true) {
    case (code.indexOf('ST1') >= 0):
        document.write('code contains "ST1"');
        break;
    case (code.indexOf('ST2') >= 0):
        document.write('code contains "ST2"');        
        break;        
    case (code.indexOf('ST3') >= 0):
        document.write('code contains "ST3"');
        break;        
    }?

How to create a checkbox with a clickable label?

You could also use CSS pseudo elements to pick and display your labels from all your checkbox's value attributes (respectively).
Edit: This will only work with webkit and blink based browsers (Chrome(ium), Safari, Opera....) and thus most mobile browsers. No Firefox or IE support here.
This may only be useful when embedding webkit/blink onto your apps.

<input type="checkbox" value="My checkbox label value" />
<style>
[type=checkbox]:after {
    content: attr(value);
    margin: -3px 15px;
    vertical-align: top;
    white-space:nowrap;
    display: inline-block;
}
</style>

All pseudo element labels will be clickable.

Demo:http://codepen.io/mrmoje/pen/oteLl, + The gist of it

What is tempuri.org?

Note that namespaces that are in the format of a valid Web URL don't necessarily need to be dereferenced i.e. you don't need to serve actual content at that URL. All that matters is that the namespace is globally unique.

break statement in "if else" - java

Because your else isn't attached to anything. The if without braces only encompasses the single statement that immediately follows it.

if (choice==5)
{
    System.out.println("End of Game\n Thank you for playing with us!");
    break;
}
else
{
   System.out.println("Not a valid choice!\n Please try again...\n");
}

Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.

In addition, using a switch here would make more sense.

int choice;
boolean keepGoing = true;
while(keepGoing)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch(choice)
    {
        case 1: 
            playGame();
            break;
        case 2: 
            loadGame();
            break;
        // your other cases
        // ...
        case 5: 
            System.out.println("End of Game\n Thank you for playing with us!");
            keepGoing = false;
            break;
        default:
            System.out.println("Not a valid choice!\n Please try again...\n");
     }
 }         

Note that instead of an infinite for loop I used a while(boolean), making it easy to exit the loop. Another approach would be using break with labels.

Limiting floats to two decimal points

You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.

With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

For example,

>>> 125650429603636838/(2**53)
13.949999999999999

>>> 234042163/(2**24)
13.949999988079071

>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999

If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:

  1. Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
  2. Or use a fixed point number like decimal.

how to automatically scroll down a html page?

You can use .scrollIntoView() for this. It will bring a specific element into the viewport.

Example:

document.getElementById( 'bottom' ).scrollIntoView();

Demo: http://jsfiddle.net/ThinkingStiff/DG8yR/

Script:

function top() {
    document.getElementById( 'top' ).scrollIntoView();    
};

function bottom() {
    document.getElementById( 'bottom' ).scrollIntoView();
    window.setTimeout( function () { top(); }, 2000 );
};

bottom();

HTML:

<div id="top">top</div>
<div id="bottom">bottom</div>

CSS:

#top {
    border: 1px solid black;
    height: 3000px;
}

#bottom {
    border: 1px solid red;
}

Does :before not work on img elements?

::after may be used to display the fallback image of an image


See the example below, first 2 img tags are point to the broken urls. But the second one displays the fallback image instead of the default broken logo from the browser. However, I'm not sure this's any practical, I find it kind of tricky to get it to work right.

_x000D_
_x000D_
img {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  vertical-align: top;_x000D_
}_x000D_
img:not(:first-child)::after {_x000D_
  position: absolute;_x000D_
  left: 0; top: 0; right: 0; bottom: 0;_x000D_
  content: "<" attr(alt) "> NOT FOUND";_x000D_
  border: 1px dashed #999;_x000D_
  background: url(https://cdn.dribbble.com/users/1012566/screenshots/4187820/topic-2.jpg) center/100%;_x000D_
}
_x000D_
<img src="https://source.unsplash.com/random/100/75" alt="logo">_x000D_
<img src="https://source.unsplash.com/random/100/75" alt="logo">_x000D_
<img src="https://source.unsplash.com/random/100x75" alt="logo">
_x000D_
_x000D_
_x000D_

Pass table as parameter into sql server UDF

You can, however no any table. From documentation:

For Transact-SQL functions, all data types, including CLR user-defined types and user-defined table types, are allowed except the timestamp data type.

You can use user-defined table types.

Example of user-defined table type:

CREATE TYPE TableType 
AS TABLE (LocationName VARCHAR(50))
GO 

DECLARE @myTable TableType
INSERT INTO @myTable(LocationName) VALUES('aaa')
SELECT * FROM @myTable

So what you can do is to define your table type, for example TableType and define the function which takes the parameter of this type. An example function:

CREATE FUNCTION Example( @TableName TableType READONLY)
RETURNS VARCHAR(50)
AS
BEGIN
    DECLARE @name VARCHAR(50)

    SELECT TOP 1 @name = LocationName FROM @TableName
    RETURN @name
END

The parameter has to be READONLY. And example usage:

DECLARE @myTable TableType
INSERT INTO @myTable(LocationName) VALUES('aaa')
SELECT * FROM @myTable

SELECT dbo.Example(@myTable)

Depending on what you want achieve you can modify this code.

EDIT: If you have a data in a table you may create a variable:

DECLARE @myTable TableType

And take data from your table to the variable

INSERT INTO @myTable(field_name)
SELECT field_name_2 FROM my_other_table

What is the difference between sed and awk?

1) What is the difference between awk and sed ?

Both are tools that transform text. BUT awk can do more things besides just manipulating text. Its a programming language by itself with most of the things you learn in programming, like arrays, loops, if/else flow control etc You can "program" in sed as well, but you won't want to maintain the code written in it.

2) What kind of application are best use cases for sed and awk tools ?

Conclusion: Use sed for very simple text parsing. Anything beyond that, awk is better. In fact, you can ditch sed altogether and just use awk. Since their functions overlap and awk can do more, just use awk. You will reduce your learning curve as well.

When to use static keyword before global variables?

The correct mechanism for C++ in anonymous namespaces. If you want something that is local to your file, you should use an anonymous namespace rather than the static modifier.

Git push rejected after feature branch rebase

I would do as below

rebase feature
git checkout -b feature2 origin/feature
git push -u origin feature2:feature2
Delete the old remote branch feature
git push -u origin feature:feature

Now the remote will have feature(rebased on latest master) and feature2(with old master head). This would allow you to compare later if you have done mistakes in reolving conflicts.