Programs & Examples On #Optional parameters

An optional parameter is one that a caller can include in a call to a function or method, but doesn't have to. When omitted, a default value is used instead. Optional parameters are useful when the default value is used in most cases, but still needs to be specified on occasion.

C# 4.0 optional out/ref arguments

No, but another great alternative is having the method use a generic template class for optional parameters as follows:

public class OptionalOut<Type>
{
    public Type Result { get; set; }
}

Then you can use it as follows:

public string foo(string value, OptionalOut<int> outResult = null)
{
    // .. do something

    if (outResult != null) {
        outResult.Result = 100;
    }

    return value;
}

public void bar ()
{
    string str = "bar";

    string result;
    OptionalOut<int> optional = new OptionalOut<int> ();

    // example: call without the optional out parameter
    result = foo (str);
    Console.WriteLine ("Output was {0} with no optional value used", result);

    // example: call it with optional parameter
    result = foo (str, optional);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);

    // example: call it with named optional parameter
    foo (str, outResult: optional);
    Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
}

How can I use optional parameters in a T-SQL stored procedure?

Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).

Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:

Dynamic Search Conditions in T-SQL by by Erland Sommarskog

The Curse and Blessings of Dynamic SQL by Erland Sommarskog

If you have the proper SQL Server 2008 version (SQL 2008 SP1 CU5 (10.0.2746) and later), you can use this little trick to actually use an index:

Add OPTION (RECOMPILE) onto your query, see Erland's article, and SQL Server will resolve the OR from within (@LastName IS NULL OR LastName= @LastName) before the query plan is created based on the runtime values of the local variables, and an index can be used.

This will work for any SQL Server version (return proper results), but only include the OPTION(RECOMPILE) if you are on SQL 2008 SP1 CU5 (10.0.2746) and later. The OPTION(RECOMPILE) will recompile your query, only the verison listed will recompile it based on the current run time values of the local variables, which will give you the best performance. If not on that version of SQL Server 2008, just leave that line off.

CREATE PROCEDURE spDoSearch
    @FirstName varchar(25) = null,
    @LastName varchar(25) = null,
    @Title varchar(25) = null
AS
    BEGIN
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
                (@FirstName IS NULL OR (FirstName = @FirstName))
            AND (@LastName  IS NULL OR (LastName  = @LastName ))
            AND (@Title     IS NULL OR (Title     = @Title    ))
        OPTION (RECOMPILE) ---<<<<use if on for SQL 2008 SP1 CU5 (10.0.2746) and later
    END

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

Because default parameters are resolved at compile time, not runtime. So the default values does not belong to the object being called, but to the reference type that it is being called through.

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

Java optional parameters

Default arguments can not be used in Java. Where in C#, C++ and Python, we can use them..

In Java, we must have to use 2 methods (functions) instead of one with default parameters.

Example:

Stash(int size); 

Stash(int size, int initQuantity);

http://parvindersingh.webs.com/apps/forums/topics/show/8856498-java-how-to-set-default-parameters-values-like-c-

Ruby optional parameters

It is possible :) Just change definition

def ldap_get ( base_dn, filter, scope=LDAP::LDAP_SCOPE_SUBTREE, attrs=nil )

to

def ldap_get ( base_dn, filter, *param_array, attrs=nil )
scope = param_array.first || LDAP::LDAP_SCOPE_SUBTREE

scope will be now in array on its first place. When you provide 3 arguments, then you will have assigned base_dn, filter and attrs and param_array will be [] When 4 and more arguments then param_array will be [argument1, or_more, and_more]

Downside is... it is unclear solution, really ugly. This is to answer that it is possible to ommit argument in the middle of function call in ruby :)

Another thing you have to do is to rewrite default value of scope.

Normal arguments vs. keyword arguments

I'm surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using *args and **kwargs (from this site):

def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

This allows you to use arbitrary keyword arguments that may have keys you don't want to define upfront.

optional parameters in SQL Server stored proc?

2014 and above at least you can set a default and it will take that and NOT error when you do not pass that parameter. Partial Example: the 3rd parameter is added as optional. exec of the actual procedure with only the first two parameters worked fine

exec getlist 47,1,0

create procedure getlist
   @convId int,
   @SortOrder int,
   @contestantsOnly bit = 0
as

What does the construct x = x || y mean?

Double pipe stands for logical "OR". This is not really the case when the "parameter not set", since strictly in the javascript if you have code like this:

function foo(par) {
}

Then calls

foo()
foo("")
foo(null)
foo(undefined)
foo(0)

are not equivalent.

Double pipe (||) will cast the first argument to boolean and if resulting boolean is true - do the assignment otherwise it will assign the right part.

This matters if you check for unset parameter.

Let's say, we have a function setSalary that has one optional parameter. If user does not supply the parameter then the default value of 10 should be used.

if you do the check like this:

function setSalary(dollars) {
    salary = dollars || 10
}

This will give unexpected result on call like

setSalary(0) 

It will still set the 10 following the flow described above.

SQL Server stored procedure parameters

SQL Server doesn't allow you to pass parameters to a procedure that you haven't defined. I think the closest you can get to this sort of design is to use optional parameters like so:

CREATE PROCEDURE GetTaskEvents
    @TaskName varchar(50),
    @ID int = NULL
AS
BEGIN
-- SP Logic
END;

You would need to include every possible parameter that you might use in the definition. Then you'd be free to call the procedure either way:

EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
EXEC GetTaskEvents @TaskName = 'TESTTASK'; -- @ID gets NULL here

How can you use optional parameters in C#?

Hello Optional World

If you want the runtime to supply a default parameter value, you have to use reflection to make the call. Not as nice as the other suggestions for this question, but compatible with VB.NET.

using System;
using System.Runtime.InteropServices;
using System.Reflection;

namespace ConsoleApplication1
{
    class Class1
    {
        public static void sayHelloTo(
            [Optional,
            DefaultParameterValue("world")] string whom)
        {
            Console.WriteLine("Hello " + whom);
        }

        [STAThread]
        static void Main(string[] args)
        {
            MethodInfo mi = typeof(Class1).GetMethod("sayHelloTo");
            mi.Invoke(null, new Object[] { Missing.Value });
        }
    }
}

Is there a way to provide named parameters in a function call in JavaScript?

Contrary to what is commonly believed, named parameters can be implemented in standard, old-school JavaScript (for boolean parameters only) by means of a simple, neat coding convention, as shown below.

function f(p1=true, p2=false) {
    ...
}

f(!!"p1"==false, !!"p2"==true); // call f(p1=false, p2=true)

Caveats:

  • Ordering of arguments must be preserved - but the pattern is still useful, since it makes it obvious which actual argument is meant for which formal parameter without having to grep for the function signature or use an IDE.

  • This only works for booleans. However, I'm sure a similar pattern could be developed for other types using JavaScript's unique type coercion semantics.

Groovy method with optional parameters

Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:

def someMethod(def args) {
    println "MANDATORY1=${args.mandatory1}"
    println "MANDATORY2=${args.mandatory2}"
    println "OPTIONAL1=${args?.optional1}"
    println "OPTIONAL2=${args?.optional2}"
}

someMethod mandatory1:1, mandatory2:2, optional1:3

with the output:

MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null

This looks nicer and the advantage of this is that you can change the order of the parameters as you like.

How to define optional methods in Swift protocol?

  • You need to add optional keyword prior to each method.
  • Please note, however, that for this to work, your protocol must be marked with the @objc attribute.
  • This further implies that this protocol would be applicable to classes but not structures.

Default value of function parameter

The first way would be preferred to the second.

This is because the header file will show that the parameter is optional and what its default value will be. Additionally, this will ensure that the default value will be the same, no matter the implementation of the corresponding .cpp file.

In the second way, there is no guarantee of a default value for the second parameter. The default value could change, depending on how the corresponding .cpp file is implemented.

How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

Android Button setOnClickListener Design

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    Button b1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(),"Button is Working",Toast.LENGTH_LONG).show();
    }

}

How to get Wikipedia content using Wikipedia's API?

You can get the introduction of the article in Wikipedia by querying pages such as https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=java. You just need to parse the json file and the result is plain text which has been cleaned including removing links and references.

how to set active class to nav menu from twitter bootstrap

<div class="nav-collapse">
                <ul class="nav">
                    <li class="home"><a href="~/Home/Index">Home</a></li>
                    <li class="Project"><a href="#">Project</a></li>
                    <li class="Customer"><a href="#">Customer</a></li>
                    <li class="Staff"><a href="#">Staff</a></li>
                    <li class="Broker"><a href="~/Home/Broker">Broker</a></li>
                    <li class="Sale"><a href="#">Sale</a></li>
                </ul>
</div>

$('ul.nav>li.home>a').click();  // first. same to all the other options changing the li class name 

Using psql to connect to PostgreSQL in SSL mode

psql below 9.2 does not accept this URL-like syntax for options.

The use of SSL can be driven by the sslmode=value option on the command line or the PGSSLMODE environment variable, but the default being prefer, SSL connections will be tried first automatically without specifying anything.

Example with a conninfo string (updated for psql 8.4)

psql "sslmode=require host=localhost dbname=test"

Read the manual page for more options.

Eclipse HotKey: how to switch between tabs?

You can use ALT+Left to go to your previous tab, or ALT+Right to go to forward. This method is using tab-switching like history, though, so it will go to the previous tab you had open, and forward if you've gone "back" once or more. A bit weird, I know, but it works. You can always "reset" the history by clicking through every tab once.

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

You do not need to set credentials in database.php file. It is enough if you have credentials in .env

If you are able to login to database directly then this password must work. It can be possible that you are having different environment than "local" which is defined in this file. Test is with "php artisan env"

How to check if a string starts with one of several prefixes?

When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:

String newStr4 = strr.split("2012")[0];
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...)
str4.add(newStr4);

WPF MVVM: How to close a window

As someone commented, the code I have posted is not MVVM friendly, how about the second solution?

1st, not MVVM solution (I will not delete this as a reference)

XAML:

<Button Name="okButton" Command="{Binding OkCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">OK</Button>

ViewModel:

public ICommand OkCommand
{
    get
    {
        if (_okCommand == null)
        {
            _okCommand = new ActionCommand<Window>(DoOk, CanDoOk);
        }
        return _okCommand ;
    }
}

void DoOk(Window win)
{
    // Your Code
    win.DialogResult = true;
    win.Close();
}

bool CanDoOk(Window win) { return true; }

2nd, probably better solution: Using attached behaviours

XAML

<Button Content="Ok and Close" Command="{Binding OkCommand}" b:CloseOnClickBehaviour.IsEnabled="True" />

View Model

public ICommand OkCommand
{
    get { return _okCommand; }
}

Behaviour Class Something similar to this:

public static class CloseOnClickBehaviour
{
    public static readonly DependencyProperty IsEnabledProperty =
        DependencyProperty.RegisterAttached(
            "IsEnabled",
            typeof(bool),
            typeof(CloseOnClickBehaviour),
            new PropertyMetadata(false, OnIsEnabledPropertyChanged)
        );

    public static bool GetIsEnabled(DependencyObject obj)
    {
        var val = obj.GetValue(IsEnabledProperty);
        return (bool)val;
    }

    public static void SetIsEnabled(DependencyObject obj, bool value)
    {
        obj.SetValue(IsEnabledProperty, value);
    }

    static void OnIsEnabledPropertyChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs args)
    {
        var button = dpo as Button;
        if (button == null)
            return;

        var oldValue = (bool)args.OldValue;
        var newValue = (bool)args.NewValue;

        if (!oldValue && newValue)
        {
            button.Click += OnClick;
        }
        else if (oldValue && !newValue)
        {
            button.PreviewMouseLeftButtonDown -= OnClick;
        }
    }

    static void OnClick(object sender, RoutedEventArgs e)
    {
        var button = sender as Button;
        if (button == null)
            return;

        var win = Window.GetWindow(button);
        if (win == null)
            return;

        win.Close();
    }

}

Linq code to select one item

I'll tell you what worked for me:

int id = int.Parse(insertItem.OwnerTableView.DataKeyValues[insertItem.ItemIndex]["id_usuario"].ToString());

var query = user.First(x => x.id_usuario == id);
tbUsername.Text = query.username;
tbEmail.Text = query.email;
tbPassword.Text = query.password;

My id is the row I want to query, in this case I got it from a radGrid, then I used it to query, but this query returns a row, then you can assign the values you got from the query to textbox, or anything, I had to assign those to textbox.

How to find a number in a string using JavaScript?

You can also try this :

_x000D_
_x000D_
var string = "border-radius:10px 20px 30px 40px";_x000D_
var numbers = string.match(/\d+/g).map(Number);_x000D_
console.log(numbers)
_x000D_
_x000D_
_x000D_

text box input height

Use CSS:

<input type="text" class="bigText"  name=" item" align="left" />

.bigText {
    height:30px;
}

Dreamweaver is a poor testing tool. It is not a browser.

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Utility of HTTP header "Content-Type: application/force-download" for mobile?

To download a file please use the following code ... Store the File name with location in $file variable. It supports all mime type

$file = "location of file to download"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

To know about Mime types please refer to this link: http://php.net/manual/en/function.mime-content-type.php

await is only valid in async function

When I got this error, it turned out I had a call to the map function inside my "async" function, so this error message was actually referring to the map function not being marked as "async". I got around this issue by taking the "await" call out of the map function and coming up with some other way of getting the expected behavior.

var myfunction = async function(x,y) {
    ....
    someArray.map(someVariable => { // <- This was the function giving the error
        return await someFunction(someVariable);
    });
}

Get current language in CultureInfo

This is what i used:

var culture = System.Globalization.CultureInfo.CurrentCulture;

and it's working :)

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

I had the same error and struggled to fix it, then answer above by Nagaraja JB helped me to fix it. In my case:

Was before: JSONObject response_json = new JSONObject(response_data);

Changed it to: JSONArray response_json = new JSONArray(response_data);

This fixed it.

Read and Write CSV files including unicode with Python 2.7

I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:

class UnicodeWriter:
def __init__(self, f, dialect=csv.excel_tab, encoding="utf-16", **kwds):
    # Redirect output to a queue
    self.queue = StringIO.StringIO()
    self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
    self.stream = f

    # Force BOM
    if encoding=="utf-16":
        import codecs
        f.write(codecs.BOM_UTF16)

    self.encoding = encoding

def writerow(self, row):
    # Modified from original: now using unicode(s) to deal with e.g. ints
    self.writer.writerow([unicode(s).encode("utf-8") for s in row])
    # Fetch UTF-8 output from the queue ...
    data = self.queue.getvalue()
    data = data.decode("utf-8")
    # ... and reencode it into the target encoding
    data = data.encode(self.encoding)

    # strip BOM
    if self.encoding == "utf-16":
        data = data[2:]

    # write to the target stream
    self.stream.write(data)
    # empty queue
    self.queue.truncate(0)

def writerows(self, rows):
    for row in rows:
        self.writerow(row)

echo key and value of an array without and with loop

Without a loop, just for the kicks of it...


You can either convert the array to a non-associative one, by doing:

$page = array_values($page);

And then acessing each element by it's zero-based index:

echo $page[0]; // 'index.html'
echo $page[1]; // 'services.html'

Or you can use a slightly more complicated version:

$value = array_slice($page, 0, 1);

echo key($value); // Home
echo current($value); // index.html

$value = array_slice($page, 1, 1);

echo key($value); // Service
echo current($value); // services.html

How can I replace non-printable Unicode characters in Java?

I propose it remove the non printable characters like below instead of replacing it

private String removeNonBMPCharacters(final String input) {
    StringBuilder strBuilder = new StringBuilder();
    input.codePoints().forEach((i) -> {
        if (Character.isSupplementaryCodePoint(i)) {
            strBuilder.append("?");
        } else {
            strBuilder.append(Character.toChars(i));
        }
    });
    return strBuilder.toString();
}

How can I mimic the bottom sheet from the Maps app?

I wrote my own library to achieve the intended behaviour in ios Maps app. It is a protocol oriented solution. So you don't need to inherit any base class instead create a sheet controller and configure as you wish. It also supports inner navigation/presentation with or without UINavigationController.

See below link for more details.

https://github.com/OfTheWolf/UBottomSheet

ubottom sheet

Regex for remove everything after | (with | )

In a .txt file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+ in the space Find what
and let the space Replace with blank

Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I think You are trying to use the normal URL of video Like this :

Copying Direct URL from YouTube

That doesn't let you display the content on other domains.To Tackle this up , You should use the Copy Embed Code feature provided by the YouTube itself .Like this :

Copy Embed Code ( YouTube )

That would free you up from any issues .

For the above Scenario :

  • Go to Youtube Video

  • Copy Embed Code

  • Paste that into your Code ( Make sure you Escape all the " ( Inverted Commas) by \" .

How to add multiple font files for the same font?

To have font variation working correctly, I had to reverse the order of @font-face in CSS.

@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-BoldOblique.ttf");
    font-weight: bold;
    font-style: italic, oblique;
}   
@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-Oblique.ttf");
    font-style: italic, oblique;
}
@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-Bold.ttf");
    font-weight: bold;
}
 @font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono.ttf");
}

Procedure or function !!! has too many arguments specified

In addition to all the answers provided so far, another reason for causing this exception can happen when you are saving data from list to database using ADO.Net.

Many developers will mistakenly use for loop or foreach and leave the SqlCommand to execute outside the loop, to avoid that make sure that you have like this code sample for example:

public static void Save(List<myClass> listMyClass)
    {
        using (var Scope = new System.Transactions.TransactionScope())
        {
            if (listMyClass.Count > 0)
            {
                for (int i = 0; i < listMyClass.Count; i++)
                {
                    SqlCommand cmd = new SqlCommand("dbo.SP_SaveChanges", myConnection);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Clear();

                    cmd.Parameters.AddWithValue("@ID", listMyClass[i].ID);
                    cmd.Parameters.AddWithValue("@FirstName", listMyClass[i].FirstName);
                    cmd.Parameters.AddWithValue("@LastName", listMyClass[i].LastName);

                    try
                    {
                        myConnection.Open();
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqe)
                    {
                        throw new Exception(sqe.Message);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        myConnection.Close();
                    }
                }
            }
            else
            {
                throw new Exception("List is empty");
            }

            Scope.Complete();
        }
    }

Laravel - Pass more than one variable to view

This is how you do it:

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();

    return $view->with('persons', $persons)->with('ms', $ms);
}

You can also use compact():

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();

    return $view->with(compact('persons', 'ms'));
}

Or do it in one line:

function view($view)
{
    return $view
            ->with('ms', Person::where('name', '=', 'Foo Bar')->first())
            ->with('persons', Person::order_by('list_order', 'ASC')->get());
}

Or even send it as an array:

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();

    return $view->with('data', ['ms' => $ms, 'persons' => $persons]));
}

But, in this case, you would have to access them this way:

{{ $data['ms'] }}

Using "If cell contains #N/A" as a formula condition.

Input the following formula in C1:

=IF(ISNA(A1),B1,A1*B1)

Screenshots:

When #N/A:

enter image description here

When not #N/A:

enter image description here

Let us know if this helps.

R - Concatenate two dataframes?

you can use the function

bind_rows(a,b)

from the dplyr library

Can't start Eclipse - Java was started but returned exit code=13

I was facing the same issue. I had installed version 8 and update 25 32 bit.

To fix, install Java SE Development Kit 7 Update 71 (64 bit). Then through appwiz.cpl, delete the other version i.e. Java Update 25. Done.

How to update SQLAlchemy row entry?

With the help of user=User.query.filter_by(username=form.username.data).first() statement you will get the specified user in user variable.

Now you can change the value of the new object variable like user.no_of_logins += 1 and save the changes with the session's commit method.

How to install pkg config in windows?

This is a step-by-step procedure to get pkg-config working on Windows, based on my experience, using the info from Oliver Zendel's comment.

I assume here that MinGW was installed to C:\MinGW. There were multiple versions of the packages available, and in each case I just downloaded the latest version.

  1. go to http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/
  2. download the file pkg-config_0.26-1_win32.zip
  3. extract the file bin/pkg-config.exe to C:\MinGW\bin
  4. download the file gettext-runtime_0.18.1.1-2_win32.zip
  5. extract the file bin/intl.dll to C:\MinGW\bin
  6. go to http://ftp.gnome.org/pub/gnome/binaries/win32/glib/2.28
  7. download the file glib_2.28.8-1_win32.zip
  8. extract the file bin/libglib-2.0-0.dll to C:\MinGW\bin

Now CMake will be able to use pkg-config if it is configured to use MinGW.

iPhone UIView Animation Best Practice

We can animate images in ios 5 using this simple code.

CGRect imageFrame = imageView.frame;
imageFrame.origin.y = self.view.bounds.size.height;

[UIView animateWithDuration:0.5
    delay:1.0
    options: UIViewAnimationCurveEaseOut
    animations:^{
        imageView.frame = imageFrame;
    } 
    completion:^(BOOL finished){
        NSLog(@"Done!");
    }];

How to import local packages without gopath

There's no such thing as "local package". The organization of packages on a disk is orthogonal to any parent/child relations of packages. The only real hierarchy formed by packages is the dependency tree, which in the general case does not reflect the directory tree.

Just use

import "myproject/packageN"

and don't fight the build system for no good reason. Saving a dozen of characters per import in any non trivial program is not a good reason, because, for example, projects with relative import paths are not go-gettable.

The concept of import paths have some important properties:

  • Import paths can be be globally unique.
  • In conjunction with GOPATH, import path can be translated unambiguously to a directory path.
  • Any directory path under GOPATH can be unambiguously translated to an import path.

All of the above is ruined by using relative import paths. Do not do it.

PS: There are few places in the legacy code in Go compiler tests which use relative imports. ATM, this is the only reason why relative imports are supported at all.

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

I use git for-each-ref to get a list of branches that are either merged or not merged into a given remote branch (e.g. origin/integration)

Iterate over all refs that match <pattern> and show them according to the given <format>, after sorting them according to the given set of <key>.

Note: replace origin/integration with integration if you tend to use git pull as opposed to git fetch.

List of local branches merged into the remote origin/integration branch

git for-each-ref --merged=origin/integration --format="%(refname:short)" refs/heads/
#                ^                           ^                           ^
#                A                           B                           C
branch1
branch2
branch3
branch4

A: Take only the branches merged into the remote origin/integration branch
B: Print the branch name
C: Only look at heads refs (i.e. branches)

List of local branches NOT merged into the remote origin/integration branch

git for-each-ref --no-merged=origin/integration --format="%(committerdate:short) %(refname:short)" --sort=committerdate refs/heads
#                ^                              ^                                                  ^                    ^
#                A                              B                                                  C                    D
2020-01-14 branch10
2020-01-16 branch11
2020-01-17 branch12
2020-01-30 branch13

A: Take only the branches NOT merged into the remote origin/integration branch
B: Print the branch name along with the last commit date
C: Sort output by commit date
D: Only look at heads refs (i.e. branches)

Html/PHP - Form - Input as array

HTML: Use names as

<input name="levels[level][]">
<input name="levels[build_time][]">

PHP:

$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
    foreach ($array[$fieldKey] as $key=>$value) {
        $newArray[$key][$fieldKey] = $value;
    }
}  

$newArray will hold data as you want

Array ( 
  [0] => Array ( [level] => 1 [build_time] => 123 ) 
  [1] => Array ( [level] => 2 [build_time] => 456 )
)

How can I drop all the tables in a PostgreSQL database?

If you have the PL/PGSQL procedural language installed you can use the following to remove everything without a shell/Perl external script.

DROP FUNCTION IF EXISTS remove_all();

CREATE FUNCTION remove_all() RETURNS void AS $$
DECLARE
    rec RECORD;
    cmd text;
BEGIN
    cmd := '';

    FOR rec IN SELECT
            'DROP SEQUENCE ' || quote_ident(n.nspname) || '.'
                || quote_ident(c.relname) || ' CASCADE;' AS name
        FROM
            pg_catalog.pg_class AS c
        LEFT JOIN
            pg_catalog.pg_namespace AS n
        ON
            n.oid = c.relnamespace
        WHERE
            relkind = 'S' AND
            n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
            pg_catalog.pg_table_is_visible(c.oid)
    LOOP
        cmd := cmd || rec.name;
    END LOOP;

    FOR rec IN SELECT
            'DROP TABLE ' || quote_ident(n.nspname) || '.'
                || quote_ident(c.relname) || ' CASCADE;' AS name
        FROM
            pg_catalog.pg_class AS c
        LEFT JOIN
            pg_catalog.pg_namespace AS n
        ON
            n.oid = c.relnamespace WHERE relkind = 'r' AND
            n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
            pg_catalog.pg_table_is_visible(c.oid)
    LOOP
        cmd := cmd || rec.name;
    END LOOP;

    FOR rec IN SELECT
            'DROP FUNCTION ' || quote_ident(ns.nspname) || '.'
                || quote_ident(proname) || '(' || oidvectortypes(proargtypes)
                || ');' AS name
        FROM
            pg_proc
        INNER JOIN
            pg_namespace ns
        ON
            (pg_proc.pronamespace = ns.oid)
        WHERE
            ns.nspname =
            'public'
        ORDER BY
            proname
    LOOP
        cmd := cmd || rec.name;
    END LOOP;

    EXECUTE cmd;
    RETURN;
END;
$$ LANGUAGE plpgsql;

SELECT remove_all();

Rather than type this in at the "psql" prompt I would suggest you copy it to a file and then pass the file as input to psql using the "--file" or "-f" options:

psql -f clean_all_pg.sql

Credit where credit is due: I wrote the function, but think the queries (or the first one at least) came from someone on one of the pgsql mailing lists years ago. Don't remember exactly when or which one.

HTML Canvas Full Screen

A - How To Calculate Full Screen Width & Height

Here is the functions;

canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

Check this out

B - How To Make Full Screen Stable With Resize

Here is the resize method for the resize event;

function resizeCanvas() {
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

    WIDTH = canvas.width;
    HEIGHT = canvas.height;

    clearScreen();
}

C - How To Get Rid Of Scroll Bars

Simply;

<style>
    html, body {
        overflow: hidden;
    }
</style>

D - Demo Code

_x000D_
_x000D_
<html>_x000D_
 <head>_x000D_
  <title>Full Screen Canvas Example</title>_x000D_
  <style>_x000D_
   html, body {_x000D_
    overflow: hidden;_x000D_
   }_x000D_
  </style>_x000D_
 </head>_x000D_
 <body onresize="resizeCanvas()">_x000D_
  <canvas id="mainCanvas">_x000D_
  </canvas>_x000D_
  <script>_x000D_
   (function () {_x000D_
    canvas = document.getElementById('mainCanvas');_x000D_
    ctx = canvas.getContext("2d");_x000D_
    _x000D_
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
    WIDTH = canvas.width;_x000D_
    HEIGHT = canvas.height;_x000D_
    _x000D_
    clearScreen();_x000D_
   })();_x000D_
   _x000D_
   function resizeCanvas() {_x000D_
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
    _x000D_
    WIDTH = canvas.width;_x000D_
    HEIGHT = canvas.height;_x000D_
    _x000D_
    clearScreen();_x000D_
   }_x000D_
   _x000D_
   function clearScreen() {_x000D_
    var grd = ctx.createLinearGradient(0,0,0,180);_x000D_
    grd.addColorStop(0,"#6666ff");_x000D_
    grd.addColorStop(1,"#aaaacc");_x000D_
_x000D_
    ctx.fillStyle = grd;_x000D_
    ctx.fillRect(  0, 0, WIDTH, HEIGHT );_x000D_
   }_x000D_
  </script>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.

var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);

C++ equivalent of StringBuffer/StringBuilder?

std::string's += doesn't work with const char* (what stuff like "string to add" appear to be), so definitely using stringstream is the closest to what is required - you just use << instead of +

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

i think csrf only works with spring forms

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

change to form:form tag and see it that works.

How to have the formatter wrap code with IntelliJ?

IntelliJ IDEA 14, 15, 2016 & 2017

Format existing code

  1. Ensure right margin is not exceeded

    File > Settings > Editor > Code Style > Java > Wrapping and Braces > Ensure right margin is not exceeded

    File Settings Ensure right margin

  2. Reformat code

    Code > Reformat code...

    Reformat code

    or press Ctrl + Alt + L

    warning If you have something like this:

    thisLineIsVeryLongAndWillBeChanged();   // comment
    

    it will be converted to

    thisLineIsVeryLongAndWillBeChanged();   
    // comment  
    

    instead of

    // comment  
    thisLineIsVeryLongAndWillBeChanged();   
    

    This is why I select pieces of code before reformatting if the code looks like in the previous example.

Wrap when typing reaches right margin

  • IntelliJ IDEA 14: File > Settings > Editor > Code Style > Wrap when typing reaches right margin

    Wrap when typing

  • IntelliJ IDEA 15, 2016 & 2017: File > Settings > Editor > Code Style > Wrap on typing

    Wrap on typing

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

Search a string in a file and delete it from this file by Shell Script

This should do it:

sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *

it will replace all occurrences of "deletethis" with "" (nothing) in all files (*), editing them in place.

In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".

The third form is the way some versions of sed like it. (e.g. Mac OS X)

man sed for more information.

Detecting installed programs via registry

Seems like looking for something specific to the installed program would work better, but HKCU\Software and HKLM\Software are the spots to look.

How to send authorization header with axios

On non-simple http requests your browser will send a "preflight" request (an OPTIONS method request) first in order to determine what the site in question considers safe information to send (see here for the cross-origin policy spec about this). One of the relevant headers that the host can set in a preflight response is Access-Control-Allow-Headers. If any of the headers you want to send were not listed in either the spec's list of whitelisted headers or the server's preflight response, then the browser will refuse to send your request.

In your case, you're trying to send an Authorization header, which is not considered one of the universally safe to send headers. The browser then sends a preflight request to ask the server whether it should send that header. The server is either sending an empty Access-Control-Allow-Headers header (which is considered to mean "don't allow any extra headers") or it's sending a header which doesn't include Authorization in its list of allowed headers. Because of this, the browser is not going to send your request and instead chooses to notify you by throwing an error.

Any Javascript workaround you find that lets you send this request anyways should be considered a bug as it is against the cross origin request policy your browser is trying to enforce for your own safety.

tl;dr - If you'd like to send Authorization headers, your server had better be configured to allow it. Set your server up so it responds to an OPTIONS request at that url with an Access-Control-Allow-Headers: Authorization header.

How to sort Counter by value? - python

More general sorted, where the key keyword defines the sorting method, minus before numerical type indicates descending:

>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x.items(), key=lambda k: -k[1])  # Ascending
[('c', 7), ('a', 5), ('b', 3)]

Use a content script to access the page context variables and functions

The only thing missing hidden from Rob W's excellent answer is how to communicate between the injected page script and the content script.

On the receiving side (either your content script or the injected page script) add an event listener:

document.addEventListener('yourCustomEvent', function (e) {
  var data = e.detail;
  console.log('received', data);
});

On the initiator side (content script or injected page script) send the event:

var data = {
  allowedTypes: 'those supported by structured cloning, see the list below',
  inShort: 'no DOM elements or classes/functions',
};

document.dispatchEvent(new CustomEvent('yourCustomEvent', { detail: data }));

Notes:

  • DOM messaging uses structured cloning algorithm, which can transfer only some types of data in addition to primitive values. It can't send class instances or functions or DOM elements.
  • In Firefox, to send an object (i.e. not a primitive value) from the content script to the page context you have to explicitly clone it into the target using cloneInto (a built-in function), otherwise it'll fail with a security violation error.

    document.dispatchEvent(new CustomEvent('yourCustomEvent', {
      detail: cloneInto(data, document.defaultView),
    }));
    

Why would we call cin.clear() and cin.ignore() after reading input?

Why do we use:

1) cin.ignore

2) cin.clear

?

Simply:

1) To ignore (extract and discard) values that we don't want on the stream

2) To clear the internal state of stream. After using cin.clear internal state is set again back to goodbit, which means that there are no 'errors'.

Long version:

If something is put on 'stream' (cin) then it must be taken from there. By 'taken' we mean 'used', 'removed', 'extracted' from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water ;)

Look at the example:

string name; //line 1
cout << "Give me your name and surname:"<<endl;//line 2
cin >> name;//line 3
int age;//line 4
cout << "Give me your age:" <<endl;//line 5
cin >> age;//line 6

What happens if the user answers: "Arkadiusz Wlodarczyk" for first question?

Run the program to see for yourself.

You will see on console "Arkadiusz" but program won't ask you for 'age'. It will just finish immediately right after printing "Arkadiusz".

And "Wlodarczyk" is not shown. It seems like if it was gone (?)*

What happened? ;-)

Because there is a space between "Arkadiusz" and "Wlodarczyk".

"space" character between the name and surname is a sign for computer that there are two variables waiting to be extracted on 'input' stream.

The computer thinks that you are tying to send to input more than one variable. That "space" sign is a sign for him to interpret it that way.

So computer assigns "Arkadiusz" to 'name' (2) and because you put more than one string on stream (input) computer will try to assign value "Wlodarczyk" to variable 'age' (!). The user won't have a chance to put anything on the 'cin' in line 6 because that instruction was already executed(!). Why? Because there was still something left on stream. And as I said earlier stream is in a flow so everything must be removed from it as soon as possible. And the possibility came when computer saw instruction cin >> age;

Computer doesn't know that you created a variable that stores age of somebody (line 4). 'age' is merely a label. For computer 'age' could be as well called: 'afsfasgfsagasggas' and it would be the same. For him it's just a variable that he will try to assign "Wlodarczyk" to because you ordered/instructed computer to do so in line (6).

It's wrong to do so, but hey it's you who did it! It's your fault! Well, maybe user, but still...


All right all right. But how to fix it?!

Let's try to play with that example a bit before we fix it properly to learn a few more interesting things :-)

I prefer to make an approach where we understand things. Fixing something without knowledge how we did it doesn't give satisfaction, don't you think? :)

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate(); //new line is here :-)

After invoking above code you will notice that the state of your stream (cin) is equal to 4 (line 7). Which means its internal state is no longer equal to goodbit. Something is messed up. It's pretty obvious, isn't it? You tried to assign string type value ("Wlodarczyk") to int type variable 'age'. Types doesn't match. It's time to inform that something is wrong. And computer does it by changing internal state of stream. It's like: "You f**** up man, fix me please. I inform you 'kindly' ;-)"

You simply cannot use 'cin' (stream) anymore. It's stuck. Like if you had put big wood logs on water stream. You must fix it before you can use it. Data (water) cannot be obtained from that stream(cin) anymore because log of wood (internal state) doesn't allow you to do so.

Oh so if there is an obstacle (wood logs) we can just remove it using tools that is made to do so?

Yes!

internal state of cin set to 4 is like an alarm that is howling and making noise.

cin.clear clears the state back to normal (goodbit). It's like if you had come and silenced the alarm. You just put it off. You know something happened so you say: "It's OK to stop making noise, I know something is wrong already, shut up (clear)".

All right let's do so! Let's use cin.clear().

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl; 
cin.clear(); //new line is here :-)
cout << cin.rdstate()<< endl;  //new line is here :-)

We can surely see after executing above code that the state is equal to goodbit.

Great so the problem is solved?

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;; 
cin.clear(); 
cout << cin.rdstate() << endl; 
cin >> age;//new line is here :-)

Even tho the state is set to goodbit after line 9 the user is not asked for "age". The program stops.

WHY?!

Oh man... You've just put off alarm, what about the wood log inside a water?* Go back to text where we talked about "Wlodarczyk" how it supposedly was gone.

You need to remove "Wlodarczyk" that piece of wood from stream. Turning off alarms doesn't solve the problem at all. You've just silenced it and you think the problem is gone? ;)

So it's time for another tool:

cin.ignore can be compared to a special truck with ropes that comes and removes the wood logs that got the stream stuck. It clears the problem the user of your program created.

So could we use it even before making the alarm goes off?

Yes:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;

The "Wlodarczyk" is gonna be removed before making the noise in line 7.

What is 10000 and '\n'?

It says remove 10000 characters (just in case) until '\n' is met (ENTER). BTW It can be done better using numeric_limits but it's not the topic of this answer.


So the main cause of problem is gone before noise was made...

Why do we need 'clear' then?

What if someone had asked for 'give me your age' question in line 6 for example: "twenty years old" instead of writing 20?

Types doesn't match again. Computer tries to assign string to int. And alarm starts. You don't have a chance to even react on situation like that. cin.ignore won't help you in case like that.

So we must use clear in case like that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

But should you clear the state 'just in case'?

Of course not.

If something goes wrong (cin >> age;) instruction is gonna inform you about it by returning false.

So we can use conditional statement to check if the user put wrong type on the stream

int age;
if (cin >> age) //it's gonna return false if types doesn't match
    cout << "You put integer";
else
    cout << "You bad boy! it was supposed to be int";

All right so we can fix our initial problem like for example that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

int age;
cout << "Give me your age:" << endl;
if (cin >> age)
  cout << "Your age is equal to:" << endl;
else
{
 cin.clear();
 cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
 cout << "Give me your age name as string I dare you";
 cin >> age;
}

Of course this can be improved by for example doing what you did in question using loop while.

BONUS:

You might be wondering. What about if I wanted to get name and surname in the same line from the user? Is it even possible using cin if cin interprets each value separated by "space" as different variable?

Sure, you can do it two ways:

1)

string name, surname;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin >> surname;

cout << "Hello, " << name << " " << surname << endl;

2) or by using getline function.

getline(cin, nameOfStringVariable);

and that's how to do it:

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

The second option might backfire you in case you use it after you use 'cin' before the getline.

Let's check it out:

a)

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endl;

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

If you put "20" as age you won't be asked for nameAndSurname.

But if you do it that way:

b)

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endll

everything is fine.

WHAT?!

Every time you put something on input (stream) you leave at the end white character which is ENTER ('\n') You have to somehow enter values to console. So it must happen if the data comes from user.

b) cin characteristics is that it ignores whitespace, so when you are reading in information from cin, the newline character '\n' doesn't matter. It gets ignored.

a) getline function gets the entire line up to the newline character ('\n'), and when the newline char is the first thing the getline function gets '\n', and that's all to get. You extract newline character that was left on stream by user who put "20" on stream in line 3.

So in order to fix it is to always invoke cin.ignore(); each time you use cin to get any value if you are ever going to use getline() inside your program.

So the proper code would be:

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cin.ignore(); // it ignores just enter without arguments being sent. it's same as cin.ignore(1, '\n') 
cout << "Your age is" << age << endl;


string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

I hope streams are more clear to you know.

Hah silence me please! :-)

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

I prefer using the value returned by System.currentTimeMillis() for all kinds of calculations and only use Calendar or Date if I need to really display a value that is read by humans. This will also prevent 99% of your daylight-saving-time bugs. :)

scp with port number specified

Hope this will help someone looking for a perfect answer

Copying a folder or file from a server with a port defined to another server or local machine

  1. Go to a directory where you have admin rights preferably your home directory on the machine where you want to copy files to
  2. Write the command below

scp -r -P port user@IP_address:/home/file/pathDirectory .

**Note:** The last . on the command directs it to copy everything in that folder to your directory of preference

How to output a comma delimited list in jinja python template?

You want your if check to be:

{% if not loop.last %}
    ,
{% endif %}

Note that you can also shorten the code by using If Expression:

{{ ", " if not loop.last else "" }}

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

You'll need to start MySQL before you can use the mysql command on your terminal. To do this, run brew services start mysql. By default, brew installs the MySQL database without a root password. To secure it run: mysql_secure_installation.

To connect run: mysql -uroot. root is the username name here.

Invoking modal window in AngularJS Bootstrap UI using JavaScript

To make angular ui $modal work with bootstrap 3 you need to overwrite the styles

.modal {
    display: block;
}
.modal-body:before,
.modal-body:after {
    display: table;
    content: " ";
}
.modal-header:before,
.modal-header:after {
    display: table;
    content: " ";
}

(The last ones are necessary if you use custom directives) and encapsulate the html with

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      <h4 class="modal-title">Modal title</h4>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

Adding rows to tbody of a table using jQuery

use this

$("#tblEntAttributes tbody").append(newRowContent);

What does the "no version information available" error from linux dynamic linker mean?

The "no version information available" means that the library version number is lower on the shared object. For example, if your major.minor.patch number is 7.15.5 on the machine where you build the binary, and the major.minor.patch number is 7.12.1 on the installation machine, ld will print the warning.

You can fix this by compiling with a library (headers and shared objects) that matches the shared object version shipped with your target OS. E.g., if you are going to install to RedHat 3.4.6-9 you don't want to compile on Debian 4.1.1-21. This is one of the reasons that most distributions ship for specific linux distro numbers.

Otherwise, you can statically link. However, you don't want to do this with something like PAM, so you want to actually install a development environment that matches your client's production environment (or at least install and link against the correct library versions.)

Advice you get to rename the .so files (padding them with version numbers,) stems from a time when shared object libraries did not use versioned symbols. So don't expect that playing with the .so.n.n.n naming scheme is going to help (much - it might help if you system has been trashed.)

You last option will be compiling with a library with a different minor version number, using a custom linking script: http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/scripts.html

To do this, you'll need to write a custom script, and you'll need a custom installer that runs ld against your client's shared objects, using the custom script. This requires that your client have gcc or ld on their production system.

Linq to SQL .Sum() without group ... into

What about:

itemsInCart.AsEnumerable().Sum(o=>o.Price);

AsEnumerable makes the difference, this query will execute locally (Linq To Objects).

Is header('Content-Type:text/plain'); necessary at all?

It is very important that you tell the browser what type of data you are sending it. The difference should be obvious. Try viewing the output of the following PHP file in your browser;

<?php
header('Content-Type:text/html');
?>
<p>Hello</p>

You will see:

hello

(note that you will get the same results if you miss off the header line in this case - text/html is php's default)

Change it to text/plain

<?php
header('Content-Type:text/plain');
?>
<p>Hello</p>

You will see:

<p>Hello</p>

Why does this matter? If you have something like the following in a php script that, for example, is used by an ajax request:

<?php
header('Content-Type:text/html');
print "Your name is " . $_GET['name']

Someone can put a link to a URL like http://example.com/test.php?name=%3Cscript%20src=%22http://example.com/eviljs%22%3E%3C/script%3E on their site, and if a user clicks it, they have exposed all their information on your site to whoever put up the link. If you serve the file as text/plain, you are safe.

Note that this is a silly example, it's more likely that the bad script tag would be added by the attacker to a field in the database or by using a form submission.

php search array key and get value

<?php

// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
  echo $search_array[20120504];
}

// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
  echo $search_array[20120504];
}

// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
  echo $search_array[20120504];
}

?>

Nginx serves .php files as downloads, instead of executing them

I had been having the same problem what solved it was this server block also have this block above other location blocks if you have css not loading issues. Which I added to my sites-available conf file.

location ~ [^/]\.php(/|$) {
fastcgi_split_path_info  ^(.+\.php)(/.+)$;
fastcgi_index            index.php;
fastcgi_pass             unix:/var/run/php/php7.3-fpm.sock;
include                  fastcgi_params;
fastcgi_param   PATH_INFO       $fastcgi_path_info;
fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

Form submit with AJAX passing form data to PHP without page refresh

<div class="container">
       <div class="row">
        <div class="col-md-3 col-sm-6 col-xs-12"></div>enter code here
          <div class="col-md-6 col-sm-6 col-xs-12">
          <div class="msg"></div>
            <form method="post" class="frm" id="form1" onsubmit="">
               <div class="form-group">
               <input type="text" class="form-control" name="fname" id="fname" placeholder="enter your first neme" required>
           <!--><span class="sp"><?php// echo $f_err;?></span><!-->
          </div>
        <div class="form-group">
               <input type="text" class="form-control" name="lname" id="lname" placeholder="enter your last neme" required>
              <!--><span class="sp"><?php// echo $l_err;?></span><!-->
             </div>
              <div class="form-group">
               <input type="text" class="form-control" name="email" id="email" placeholder="enter your email Address" required>
              <!--><span class="sp"><?php// echo $e_err;?></span><!-->
             </div>
             <div class="form-group">
               <input type="number" class="form-control" name="mno" id="mno" placeholder="enter your mobile number" required>
              <!--><span class="sp"><?php //echo $m_err;?></span><!-->
             </div>
              <div class="form-group">
               <input type="password" class="form-control" name="pass" id="pass" pattern="(?=.*[a-z])(?=.*[A-Z]).{4,8}" placeholder="enter your Password" required>
              <!--><span class="sp"><?php //echo $p_err;?></span><!-->
             </div>
              <div class="radio">
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="male" name="gender" id="gender" checked>male<br>
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="female" name="gender" id="gender">female<br>
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" value="other" name="gender" id="gender">other<br>
                                         <!--><span class="sp"> <?php //echo $r_err;?></span><!-->
             </div>
                <div class="checkbox">
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" name="check" id="check" checked>I Agree Turms&Condition<br>
                   <!--><span class="sp"> <?php //echo $c_err;?></span><!-->
                 </div>
                 <input type="submit"  class="btn btn-warning" name="submit" id="submit">
             </form>enter code here

          </div>
               <div class="col-md-3 col-sm-6 col-xs-12"></div>
         </div> 

    </div>

how to call a function from another function in Jquery

wrap you shared code into another function:

<script>
  function myFun () {
      //do something
  }

  $(document).ready(function(){
    //Load City by State
    $(document).on('change', '#billing_state_id', function() {
       myFun ();
    });   
    $(document).on('click', '#click_me', function() {
       //do something
       myFun();
    });   
  });
</script>

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

How to create a DataTable in C# and how to add rows?

You can also pass in an object array as well, like so:

DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);

Or even:

dt.Rows.Add(new object[] { "Ravi", 500 });

How do you Change a Package's Log Level using Log4j?

Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.

Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).

In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:

log4j.rootLogger=DEBUG, R 
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${catalina.home}/logs/tomcat.log 
log4j.appender.R.MaxFileSize=10MB 
log4j.appender.R.MaxBackupIndex=10 
log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Simplest would be to change the line:

log4j.rootLogger=DEBUG, R

To something like:

log4j.rootLogger=WARN, R

But if you still want your own DEBUG level output from your own classes add a line that says:

log4j.category.com.mypackage=DEBUG

Reading up a bit on Log4J and Commons-Logging will help you understand all this.

MySQL error 1241: Operand should contain 1 column(s)

Just remove the ( and the ) on your SELECT statement:

insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;

Switch with if, else if, else, and loops inside case

If you need the for statement to contain only the if, you need to remove its else, like this:

for(int i=0; i<something_in_the_array.length;i++)
    if(whatever_value==(something_in_the_array[i]))
    {
        value=2;
        break;
    }

    /*this "else" must go*/
    if(whatever_value==2)
    {
        value=3;
        break;
    }

    else if(whatever_value==3)
    {
        value=4;
        break;
    }

Detecting negative numbers

if ($profitloss < 0)
{
   echo "The profitloss is negative";
}

Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.

In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:

$turnover = 10000;
$overheads = 12500;

$difference = abs($turnover-$overheads);

echo "The Difference is ".$difference;

This would produce The Difference is 2500.

Select every Nth element in CSS

You need the correct argument for the nth-child pseudo class.

  • The argument should be in the form of an + b to match every ath child starting from b.

  • Both a and b are optional integers and both can be zero or negative.

    • If a is zero then there is no "every ath child" clause.
    • If a is negative then matching is done backwards starting from b.
    • If b is zero or negative then it is possible to write equivalent expression using positive b e.g. 4n+0 is same as 4n+4. Likewise 4n-1 is same as 4n+3.

Examples:

Select every 4th child (4, 8, 12, ...)

_x000D_
_x000D_
li:nth-child(4n) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select every 4th child starting from 1 (1, 5, 9, ...)

_x000D_
_x000D_
li:nth-child(4n+1) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select every 3rd and 4th child from groups of 4 (3 and 4, 7 and 8, 11 and 12, ...)

_x000D_
_x000D_
/* two selectors are required */_x000D_
li:nth-child(4n+3),_x000D_
li:nth-child(4n+4) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Select first 4 items (4, 3, 2, 1)

_x000D_
_x000D_
/* when a is negative then matching is done backwards  */_x000D_
li:nth-child(-n+4) {_x000D_
  background: yellow;_x000D_
}
_x000D_
<ol>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Clear form fields with jQuery

$(document).ready(function() {
    $('#reset').click(function() {
    $('#compose_form').find("input[type=text] , textarea ").each(function() {
    $(this).val('');
   });
  });
});  

Make Https call using HttpClient

I agree with felickz but also i want to add an example for clarifying the usage in c#. I use SSL in windows service as follows.

    var certificatePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "bin");
    gateway = new GatewayService();
    gateway.PreAuthenticate = true;


    X509Certificate2 cert = new X509Certificate2(certificatePath + @"\Attached\my_certificate.pfx","certificate_password");
    gateway.ClientCertificates.Add(cert);

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    gateway.UserAgent = Guid.NewGuid().ToString();
    gateway.Timeout = int.MaxValue;

If I'm going to use it in a web application, I'm just changing the implementation on the proxy side like this:

public partial class GatewayService : System.Web.Services.Protocols.SoapHttpClientProtocol // to => Microsoft.Web.Services2.WebServicesClientProtocol

How do I specify the JDK for a GlassFish domain?

Similar error with Glassfish 4.0 and several JDK installed:

SEVERE: GlassFish requires JDK 7, you are using JDK version 6.

There is no AS_JAVA reference in "C:\glassfish\config\asenv.bat" by default. After adding manually

set AS_JAVA=C:\Program Files\Java\jdk1.7.0_25 

it works.

The import android.support cannot be resolved

I have resolved it by deleting android-support-v4.jar from my Project. Because appcompat_v7 already have a copy of it.

If you have already import appcompat_v7 but still the problem doesn't solve. then try it.

How to check for valid email address?

This is typically solved using regex. There are many variations of solutions however. Depending on how strict you need to be, and if you have custom requirements for validation, or will accept any valid email address.

See this page for reference: http://www.regular-expressions.info/email.html

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

  • public : it is a access specifier that means it will be accessed by publically.
  • static : it is access modifier that means when the java program is load then it will create the space in memory automatically.
  • void : it is a return type i.e it does not return any value.
  • main() : it is a method or a function name.
  • string args[] : its a command line argument it is a collection of variables in the string format.

Differentiate between function overloading and function overriding

In addition to the existing answers, Overridden functions are in different scopes; whereas overloaded functions are in same scope.

How do you add a JToken to an JObject?

TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

  • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
  • JValue = any Json value type (string, int, boolean).
  • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
  • JContainer = The mother of all types which contain other types (JObject, JValue).
  • JObject = a JContainer type that holds a collection of JProperties
  • JArray = a JContainer type that holds a collection JValue or JContainer.

Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

This is the code I modified.

public class Program
{
  public static void Main()
  {
    try
    {
      string jsonText = @"
      {
        ""food"": {
          ""fruit"": {
            ""apple"": {
              ""colour"": ""red"",
              ""size"": ""small""
            },
            ""orange"": {
              ""colour"": ""orange"",
              ""size"": ""large""
            }
          }
        }
      }";

      var foodJsonObj = JObject.Parse(jsonText);
      var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");

      var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
      fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));

      Console.WriteLine(foodJsonObj.ToString());
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
  }
}

The definitive guide to form-based website authentication

My favourite rule in regards to authentication systems: use passphrases, not passwords. Easy to remember, hard to crack. More info: Coding Horror: Passwords vs. Pass Phrases

How to add a footer in ListView?

I know this is a very old question, but I googled my way here and found the answer provided not 100% satisfying, because as gcl1 mentioned - this way the footer is not really a footer to the screen - it's just an "add-on" to the list.

Bottom line - for others who may google their way here - I found the following suggestion here: Fixed and always visible footer below ListFragment

Try doing as follows, where the emphasis is on the button (or any footer element) listed first in the XML - and then the list is added as "layout_above":

<RelativeLayout>

<Button android:id="@+id/footer" android:layout_alignParentBottom="true"/> 
<ListView android:id="@android:id/list" **android:layout_above**="@id/footer"> <!-- the list -->

</RelativeLayout>

Difference between INNER JOIN and LEFT SEMI JOIN

Trying to depict with venn diagrams for better understanding..

Left Semi join : A semi join returns values from the left side of the relation that has a match with the right. It is also referred to as a left semi join.

enter image description here

Note : There is another thing called left anti join : An anti join returns values from the left relation that has no match with the right. It is also referred to as a left anti join.

Inner join : It selects rows that have matching values in both relations.

enter image description here

How to set base url for rest in spring boot?

Since this is the first google hit for the problem and I assume more people will search for this. There is a new option since Spring Boot '1.4.0'. It is now possible to define a custom RequestMappingHandlerMapping that allows to define a different path for classes annotated with @RestController

A different version with custom annotations that combines @RestController with @RequestMapping can be found at this blog post

@Configuration
public class WebConfig {

    @Bean
    public WebMvcRegistrationsAdapter webMvcRegistrationsHandlerMapping() {
        return new WebMvcRegistrationsAdapter() {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                return new RequestMappingHandlerMapping() {
                    private final static String API_BASE_PATH = "api";

                    @Override
                    protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
                        Class<?> beanType = method.getDeclaringClass();
                        if (AnnotationUtils.findAnnotation(beanType, RestController.class) != null) {
                            PatternsRequestCondition apiPattern = new PatternsRequestCondition(API_BASE_PATH)
                                    .combine(mapping.getPatternsCondition());

                            mapping = new RequestMappingInfo(mapping.getName(), apiPattern,
                                    mapping.getMethodsCondition(), mapping.getParamsCondition(),
                                    mapping.getHeadersCondition(), mapping.getConsumesCondition(),
                                    mapping.getProducesCondition(), mapping.getCustomCondition());
                        }

                        super.registerHandlerMethod(handler, method, mapping);
                    }
                };
            }
        };
    }
}

Bootstrap 4 card-deck with number of columns based on viewport

Here's a solution with Sass to configure the number of cards per line depending on breakpoints: https://codepen.io/migli/pen/OQVRMw

It works fine with Bootstrap 4 beta 3

// Bootstrap 4 breakpoints & gutter
$grid-breakpoints: (
    xs: 0,
    sm: 576px,
    md: 768px,
    lg: 992px,
    xl: 1200px
) !default;

$grid-gutter-width: 30px !default;

// number of cards per line for each breakpoint
$cards-per-line: (
    xs: 1,
    sm: 2,
    md: 3,
    lg: 4,
    xl: 5
);

@each $name, $breakpoint in $grid-breakpoints {
    @media (min-width: $breakpoint) {
        .card-deck .card {
            flex: 0 0 calc(#{100/map-get($cards-per-line, $name)}% - #{$grid-gutter-width});
        }
    }
}

EDIT (2019/10)

I worked on another solution which uses horizontal lists group + flex utilities instead of card-deck:

https://codepen.io/migli/pen/gOOmYLb

It's an easy solution to organize any kind of elements into responsive grid

<div class="container">
    <ul class="list-group list-group-horizontal align-items-stretch flex-wrap">
        <li class="list-group-item">Cras justo odio</li>
        <li class="list-group-item">Dapibus ac facilisis in</li>
        <li class="list-group-item">Morbi leo risus</li>
        <li class="list-group-item">Cras justo odio</li>
        <li class="list-group-item">Dapibus ac facilisis in</li>
        <!--= add as many items as you need  =-->
    </ul>
</div>
.list-group-item {
    width: 95%;
    margin: 1% !important;
}

@media (min-width: 576px) {
    .list-group-item {
        width: 47%;
        margin: 5px 1.5% !important;
    }
}

@media (min-width: 768px) {
    .list-group-item {
        width: 31.333%;
        margin: 5px 1% !important;
    }
}

@media (min-width: 992px) {
    .list-group-item {
        width: 23%;
        margin: 5px 1% !important;
    }
}

@media (min-width: 1200px) {
    .list-group-item {
        width: 19%;
        margin: 5px .5% !important;
    }
}

Invert colors of an image in CSS or JavaScript

You can apply the style via javascript. This is the Js code below that applies the filter to the image with the ID theImage.

function invert(){
document.getElementById("theImage").style.filter="invert(100%)";
}

And this is the

<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png"></img>

Now all you need to do is call invert() We do this when the image is clicked.

_x000D_
_x000D_
function invert(){_x000D_
document.getElementById("theImage").style.filter="invert(100%)";_x000D_
}
_x000D_
<h4> Click image to invert </h4>_x000D_
_x000D_
<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png" onClick="invert()" ></img>
_x000D_
_x000D_
_x000D_

We use this on our website

Is it possible to use "return" in stored procedure?

Use FUNCTION:

CREATE OR REPLACE FUNCTION test_function
RETURN VARCHAR2 IS

BEGIN
  RETURN 'This is being returned from a function';
END test_function;

Using .otf fonts on web browsers

From the Google Font Directory examples:

@font-face {
  font-family: 'Tangerine';
  font-style: normal;
  font-weight: normal;
  src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
  font-family: 'Tangerine', serif;
  font-size: 48px;
}

This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf

Here are some good sites:

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

If you are using Sql Management Studio, just start it as Administrator.

Right click->Run as Administrator

How to checkout in Git by date?

To those who prefer a pipe to command substitution

git rev-list -n1 --before=2013-7-4 master | xargs git checkout

How can I limit the visible options in an HTML <select> dropdown?

Tnx @Raj_89 , Your trick was very good , can be better , only by use extra style , that make it on other dom objects , exactly like a common select option tag in html ...

select{
 position:absolute;
}

u can see result here : http://jsfiddle.net/aTzc2/

How to get MD5 sum of a string using python?

For Python 2.x, use python's hashlib

import hashlib
m = hashlib.md5()
m.update("000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite")
print m.hexdigest()

Output: a02506b31c1cd46c2e0b6380fb94eb3d

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

Just need to define yy-mm-dd here. dateFormat

Default is mm-dd-yy

Change mm-dd-yy to yy-mm-dd. Look example below

  $(function() {
    $( "#datepicker" ).datepicker({
      dateFormat: 'yy-mm-dd',
      changeMonth: true,
      changeYear: true
    });
  } );

Date: <input type="text" id="datepicker">

Better way to remove specific characters from a Perl string

You could use the tr instead:

       $p =~ tr/fo//d;

will delete every f and every o from $p. In your case it should be:

       $p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d

See Perl's tr documentation.

tr/SEARCHLIST/REPLACEMENTLIST/cdsr

Transliterates all occurrences of the characters found (or not found if the /c modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.

[…]

If the /d modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

For fixing such an issue I have used below code

a.divide(b, 2, RoundingMode.HALF_EVEN)

2 is precision. Now problem was resolved.

Import Error: No module named numpy

For those using python 2.7, should try:

apt-get install -y python-numpy

Instead of pip install numpy

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:

RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);

There, &rect is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.

The code should create a dynamic variable:

RectInvoice *rect =  new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);

There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.

Cheers

How to cast an object in Objective-C

((SelectionListViewController *)myEditController).list

More examples:

int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I was having the same problem with requests (the python library). It happened to be the accept-encoding header.

It was set this way: 'accept-encoding': 'gzip, deflate, br'

I simply removed it from the request and stopped getting the error.

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

How to create a file in memory for user to download, but not through server?

For me this worked perfectly, with the same filename and extension getting downloaded

<a href={"data:application/octet-stream;charset=utf-16le;base64," + file64 } download={title} >{title}</a>

'title' is the file name with extension i.e, sample.pdf, waterfall.jpg, etc..

'file64' is the base64 content something like this i.e, Ww6IDEwNDAsIFNsaWRpbmdTY2FsZUdyb3VwOiAiR3JvdXAgQiIsIE1lZGljYWxWaXNpdEZsYXRGZWU6IDM1LCBEZW50YWxQYXltZW50UGVyY2VudGFnZTogMjUsIFByb2NlZHVyZVBlcmNlbnQ6IDcwLKCFfSB7IkdyYW5kVG90YWwiOjEwNDAsIlNsaWRpbmdTY2FsZUdyb3VwIjoiR3JvdXAgQiIsIk1lZGljYWxWaXNpdEZsYXRGZWUiOjM1LCJEZW50YWxQYXltZW50UGVyY2VudGFnZSI6MjUsIlByb2NlZHVyZVBlcmNlbnQiOjcwLCJDcmVhdGVkX0J5IjoiVGVycnkgTGVlIiwiUGF0aWVudExpc3QiOlt7IlBhdGllbnRO

javax.websocket client simple example

Use this library org.java_websocket

First thing you should import that library in build.gradle

repositories {
 mavenCentral()
 }

then add the implementation in dependency{}

implementation "org.java-websocket:Java-WebSocket:1.3.0"

Then you can use this code

In your activity declare object for Websocketclient like

private WebSocketClient mWebSocketClient;

then add this method for callback

 private void ConnectToWebSocket() {
URI uri;
try {
    uri = new URI("ws://your web socket url");
} catch (URISyntaxException e) {
    e.printStackTrace();
    return;
}

mWebSocketClient = new WebSocketClient(uri) {
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        Log.i("Websocket", "Opened");
        mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
    }

    @Override
    public void onMessage(String s) {
        final String message = s;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView textView = (TextView)findViewById(R.id.edittext_chatbox);
                textView.setText(textView.getText() + "\n" + message);
            }
        });
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        Log.i("Websocket", "Closed " + s);
    }

    @Override
    public void onError(Exception e) {
        Log.i("Websocket", "Error " + e.getMessage());
    }
};
mWebSocketClient.connect();

}

Python 3.6 install win32api?

Take a look at this answer: ImportError: no module named win32api

You can use

pip install pypiwin32

Default FirebaseApp is not initialized

My problem was not resolved with this procedure

FirebaseApp.initializeApp(this); 

So I tried something else and now my firebase has been successfully initialized. Try adding following in app module.gradle

BuildScript{
dependencies {..
classpath : "com.google.firebase:firebase-plugins:1.1.5"
    ..}
}

dependencies {...
implementation : "com.google.firebase:firebase-perf:16.1.0"
implementation : "com.google.firebase:firebase-core:16.0.3"
..}

Pretty printing XML in Python

Use etree.indent and etree.tostring

import lxml.etree as etree

root = etree.fromstring('<html><head></head><body><h1>Welcome</h1></body></html>')
etree.indent(root, space="  ")
xml_string = etree.tostring(root, pretty_print=True).decode()
print(xml_string)

output

<html>
  <head/>
  <body>
    <h1>Welcome</h1>
  </body>
</html>

Removing namespaces and prefixes

import lxml.etree as etree


def dump_xml(element):
    for item in element.getiterator():
        item.tag = etree.QName(item).localname

    etree.cleanup_namespaces(element)
    etree.indent(element, space="  ")
    result = etree.tostring(element, pretty_print=True).decode()
    return result


root = etree.fromstring('<cs:document xmlns:cs="http://blabla.com"><name>hello world</name></cs:document>')
xml_string = dump_xml(root)
print(xml_string)

output

<document>
  <name>hello world</name>
</document>

Remove all non-"word characters" from a String in Java, leaving accented characters?

Well, here is one solution I ended up with, but I hope there's a more elegant one...

StringBuilder result = new StringBuilder();
for(int i=0; i<name.length(); i++) {
    char tmpChar = name.charAt( i );
    if (Character.isLetterOrDigit( tmpChar) || tmpChar == '_' ) {
        result.append( tmpChar );
    }
}

result ends up with the desired result...

How can I simulate an array variable in MySQL?

Nowadays using a JSON array would be an obvious answer.

Since this is an old but still relevant question I produced a short example. JSON functions are available since mySQL 5.7.x / MariaDB 10.2.3

I prefer this solution over ELT() because it's really more like an array and this 'array' can be reused in the code.

But be careful: It (JSON) is certainly much slower than using a temporary table. Its just more handy. imo.

Here is how to use a JSON array:

SET @myjson = '["gmail.com","mail.ru","arcor.de","gmx.de","t-online.de",
                "web.de","googlemail.com","freenet.de","yahoo.de","gmx.net",
                "me.com","bluewin.ch","hotmail.com","hotmail.de","live.de",
                "icloud.com","hotmail.co.uk","yahoo.co.jp","yandex.ru"]';

SELECT JSON_LENGTH(@myjson);
-- result: 19

SELECT JSON_VALUE(@myjson, '$[0]');
-- result: gmail.com

And here a little example to show how it works in a function/procedure:

DELIMITER //
CREATE OR REPLACE FUNCTION example() RETURNS varchar(1000) DETERMINISTIC
BEGIN
  DECLARE _result varchar(1000) DEFAULT '';
  DECLARE _counter INT DEFAULT 0;
  DECLARE _value varchar(50);

  SET @myjson = '["gmail.com","mail.ru","arcor.de","gmx.de","t-online.de",
                "web.de","googlemail.com","freenet.de","yahoo.de","gmx.net",
                "me.com","bluewin.ch","hotmail.com","hotmail.de","live.de",
                "icloud.com","hotmail.co.uk","yahoo.co.jp","yandex.ru"]';

  WHILE _counter < JSON_LENGTH(@myjson) DO
    -- do whatever, e.g. add-up strings...
    SET _result = CONCAT(_result, _counter, '-', JSON_VALUE(@myjson, CONCAT('$[',_counter,']')), '#');

    SET _counter = _counter + 1;
  END WHILE;

  RETURN _result;
END //
DELIMITER ;

SELECT example();

Relative URLs in WordPress

should use get_home_url(), then your links are absolute, but it does not affect if you change the site url

How do I get the HTML code of a web page in PHP?

I tried this code and it's working for me .

$html = file_get_contents('www.google.com');
$myVar = htmlspecialchars($html, ENT_QUOTES);
echo($myVar);

Grouping functions (tapply, by, aggregate) and the *apply family

On the side note, here is how the various plyr functions correspond to the base *apply functions (from the intro to plyr document from the plyr webpage http://had.co.nz/plyr/)

Base function   Input   Output   plyr function 
---------------------------------------
aggregate        d       d       ddply + colwise 
apply            a       a/l     aaply / alply 
by               d       l       dlply 
lapply           l       l       llply  
mapply           a       a/l     maply / mlply 
replicate        r       a/l     raply / rlply 
sapply           l       a       laply 

One of the goals of plyr is to provide consistent naming conventions for each of the functions, encoding the input and output data types in the function name. It also provides consistency in output, in that output from dlply() is easily passable to ldply() to produce useful output, etc.

Conceptually, learning plyr is no more difficult than understanding the base *apply functions.

plyr and reshape functions have replaced almost all of these functions in my every day use. But, also from the Intro to Plyr document:

Related functions tapply and sweep have no corresponding function in plyr, and remain useful. merge is useful for combining summaries with the original data.

Attaching click to anchor tag in angular

<a href="#" (click)="onGoToPage2()">Go to page 2</a>

Complexities of binary tree traversals

In-order, Pre-order, and Post-order traversals are Depth-First traversals.

For a Graph, the complexity of a Depth First Traversal is O(n + m), where n is the number of nodes, and m is the number of edges.

Since a Binary Tree is also a Graph, the same applies here. The complexity of each of these Depth-first traversals is O(n+m).

Since the number of edges that can originate from a node is limited to 2 in the case of a Binary Tree, the maximum number of total edges in a Binary Tree is n-1, where n is the total number of nodes.

The complexity then becomes O(n + n-1), which is O(n).

Use tnsnames.ora in Oracle SQL Developer

  • In SQLDeveloper browse Tools --> Preferences, as shown in below image.

    SQLDeveloper access preferences

  • In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory where tnsnames.ora present.
  • Then click on Ok, as shown in below diagram.
    tnsnames.ora available at Drive:\oracle\product\10x.x.x\client_x\NETWORK\ADMIN

    SQLDeveloper update tnsnames directory

Now you can connect via the TNSnames options.

Create an ArrayList of unique values

Solution #1: HashSet

A good solution to the immediate problem of reading a file into an ArrayList with a uniqueness constraint is to simply keep a HashSet of seen items. Before processing a line, we check that its key is not already in the set. If it isn't, we add the key to the set to mark it as finished, then add the line data to the result ArrayList.

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) 
        throws FileNotFoundException, IOException {

        String file = "prova.txt";
        ArrayList<String[]> data = new ArrayList<>();
        HashSet<String> seen = new HashSet<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            for (String line; (line = br.readLine()) != null;) {
                String[] split = line.split("\\s+");
                String key = split[0] + " " + split[1];

                if (!seen.contains(key)) {
                    data.add(Arrays.copyOfRange(split, 2, split.length));
                    seen.add(key);
                }
            }
        }

        for (String[] row : data) {
            System.out.println(Arrays.toString(row));
        }
    }
}

Solution #2: LinkedHashMap/LinkedHashSet

Since we have key-value pairs in this particular dataset, we could roll everything into a LinkedHashMap<String, ArrayList<String>> (see docs for LinkedHashMap) which preserves ordering but can't be indexed into (use-case driven decision, but amounts to the same strategy as above. ArrayList<String> or String[] is arbitrary here--it could be any data value). Note that this version makes it easy to preserve the most recently seen key rather than the oldest (remove the !data.containsKey(key) test).

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) 
        throws FileNotFoundException, IOException {

        String file = "prova.txt";
        LinkedHashMap<String, ArrayList<String>> data = new LinkedHashMap<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            for (String line; (line = br.readLine()) != null;) {
                String[] split = line.split("\\s+");
                String key = split[0] + " " + split[1];

                if (!data.containsKey(key)) {
                    ArrayList<String> val = new ArrayList<>();
                    String[] sub = Arrays.copyOfRange(split, 2, split.length); 
                    Collections.addAll(val, sub);
                    data.put(key, val);
                }
            }
        }

        for (Map.Entry<String, ArrayList<String>> e : data.entrySet()) {
            System.out.println(e.getKey() + " => " + e.getValue());
        }
    }
}

Solution #3: ArrayListSet

The above examples represent pretty narrow use cases. Here's a sketch for a general ArrayListSet class, which maintains the usual list behavior (add/set/remove etc) while preserving uniqueness.

Basically, the class is an abstraction of solution #1 in this post (HashSet combined with ArrayList), but with a slightly different flavor (the data itself is used to determine uniqueness rather than a key, but it's a truer "ArrayList" structure).

This class solves the problems of efficiency (ArrayList#contains is linear, so we should reject that solution except in trivial cases), lack of ordering (storing everything directly in a HashSet doesn't help us), lack of ArrayList operations (LinkedHashSet is otherwise the best solution but we can't index into it, so it's not a true replacement for an ArrayList).

Using a HashMap<E, index> instead of a HashSet would speed up remove(Object o) and indexOf(Object o) functions (but slow down sort). A linear remove(Object o) is the main drawback over a plain HashSet.

import java.util.*;

public class ArrayListSet<E> implements Iterable<E>, Set<E> {
    private ArrayList<E> list;
    private HashSet<E> set;

    public ArrayListSet() {
        list = new ArrayList<>();
        set = new HashSet<>();
    }

    public boolean add(E e) {
        return set.add(e) && list.add(e);
    }

    public boolean add(int i, E e) {
        if (!set.add(e)) return false;
        list.add(i, e);
        return true;
    }

    public void clear() {
        list.clear();
        set.clear();
    }

    public boolean contains(Object o) {
        return set.contains(o);
    }

    public E get(int i) {
        return list.get(i);
    }

    public boolean isEmpty() {
        return list.isEmpty();
    }

    public E remove(int i) {        
        E e = list.remove(i);
        set.remove(e);
        return e;
    }

    public boolean remove(Object o) {        
        if (set.remove(o)) {
            list.remove(o);
            return true;
        }

        return false;
    }

    public boolean set(int i, E e) {
        if (set.contains(e)) return false;

        set.add(e);
        set.remove(list.set(i, e));
        return true;
    }

    public int size() {
        return list.size();
    }

    public void sort(Comparator<? super E> c) {
        Collections.sort(list, c);
    }

    public Iterator<E> iterator() {
        return list.iterator();
    }

    public boolean addAll(Collection<? extends E> c) {
        int before = size();
        for (E e : c) add(e);
        return size() == before;
    }

    public boolean containsAll(Collection<?> c) {
        return set.containsAll(c);
    }

    public boolean removeAll(Collection<?> c) {
        return set.removeAll(c) && list.removeAll(c);
    }

    public boolean retainAll(Collection<?> c) {
         return set.retainAll(c) && list.retainAll(c);
    }

    public Object[] toArray() {
        return list.toArray();
    }

    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }
}

Example usage:

public class ArrayListSetDriver {
    public static void main(String[] args) {
        ArrayListSet<String> fruit = new ArrayListSet<>();
        fruit.add("apple");
        fruit.add("banana");
        fruit.add("kiwi");
        fruit.add("strawberry");
        fruit.add("apple");
        fruit.add("strawberry");

        for (String item : fruit) {
            System.out.print(item + " "); // => apple banana kiwi strawberry
        }

        fruit.remove("kiwi");
        fruit.remove(1);
        fruit.add(0, "banana");
        fruit.set(2, "cranberry");
        fruit.set(0, "cranberry");
        System.out.println();

        for (int i = 0; i < fruit.size(); i++) {
            System.out.print(fruit.get(i) + " "); // => banana apple cranberry
        }

        System.out.println();
    }
}

Solution #4: ArrayListMap

This class solves a drawback of ArrayListSet which is that the data we want to store and its associated key may not be the same. This class provides a put method that enforces uniqueness on a different object than the data stored in the underlying ArrayList. This is just what we need to solve the original problem posed in this thread. This gives us the ordering and iteration of an ArrayList but fast lookups and uniqueness properties of a HashMap. The HashMap contains the unique values mapped to their index locations in the ArrayList, which enforces ordering and provides iteration.

This approach solves the scalability problems of using a HashSet in solution #1. That approach works fine for a quick file read, but without an abstraction, we'd have to handle all consistency operations by hand and pass around multiple raw data structures if we needed to enforce that contract across multiple functions and over time.

As with ArrayListSet, this can be considered a proof of concept rather than a full implementation.

import java.util.*;

public class ArrayListMap<K, V> implements Iterable<V>, Map<K, V> {
    private ArrayList<V> list;
    private HashMap<K, Integer> map;

    public ArrayListMap() {
        list = new ArrayList<>();
        map = new HashMap<>();
    }

    public void clear() {
        list.clear();
        map.clear();
    }

    public boolean containsKey(Object key) {
        return map.containsKey(key);
    }

    public boolean containsValue(Object value) {
        return list.contains(value);
    }

    public V get(int i) {
        return list.get(i);
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    public V get(Object key) {
        return list.get(map.get(key));
    }

    public V put(K key, V value) {
        if (map.containsKey(key)) {
            int i = map.get(key);
            V v = list.get(i);
            list.set(i, value);
            return v;
        }

        list.add(value);
        map.put(key, list.size() - 1);
        return null;
    }

    public V putIfAbsent(K key, V value) {
        if (map.containsKey(key)) {
            if (list.get(map.get(key)) == null) {
                list.set(map.get(key), value);
                return null;
            }

            return list.get(map.get(key));
        }

        return put(key, value);
    }

    public V remove(int i) {
        V v = list.remove(i);

        for (Map.Entry<K, Integer> entry : map.entrySet()) {
            if (entry.getValue() == i) {
                map.remove(entry.getKey());
                break;
            }
        }

        decrementMapIndices(i);
        return v;
    }

    public V remove(Object key) {
        if (map.containsKey(key)) {
            int i = map.remove(key);
            V v = list.get(i);
            list.remove(i);
            decrementMapIndices(i);
            return v;
        }

        return null;
    }

    private void decrementMapIndices(int start) {
        for (Map.Entry<K, Integer> entry : map.entrySet()) {
            int i = entry.getValue();

            if (i > start) {
                map.put(entry.getKey(), i - 1);
            }
        }
    }

    public int size() {
        return list.size();
    }

    public void putAll(Map<? extends K, ? extends V> m) {
        for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
            put(entry.getKey(), entry.getValue());
        }
    }

    public Set<Map.Entry<K, V>> entrySet() {
        Set<Map.Entry<K, V>> es = new HashSet<>();

        for (Map.Entry<K, Integer> entry : map.entrySet()) {
            es.add(new AbstractMap.SimpleEntry<>(
                entry.getKey(), list.get(entry.getValue())
            ));
        }

        return es;
    }

    public Set<K> keySet() {
        return map.keySet();
    }

    public Collection<V> values() {
        return list;
    }

    public Iterator<V> iterator() {
        return list.iterator();
    }

    public Object[] toArray() {
        return list.toArray();
    }

    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }
}

Here's the class in action on the original problem:

import java.io.*;

public class Main {
    public static void main(String[] args) 
        throws FileNotFoundException, IOException {

        String file = "prova.txt";
        ArrayListMap<String, String[]> data = new ArrayListMap<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            for (String line; (line = br.readLine()) != null;) {
                String[] split = line.split("\\s+");
                String key = split[0] + " " + split[1];
                String[] sub = Arrays.copyOfRange(split, 2, split.length); 
                data.putIfAbsent(key, sub); 
            }
        }

        for (Map.Entry<String, String[]> e : data.entrySet()) {
            System.out.println(e.getKey() + " => " + 
                java.util.Arrays.toString(e.getValue()));
        }

        for (String[] a : data) {
            System.out.println(java.util.Arrays.toString(a));
        }
    }
}

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

This answer might be helpful if you see above error but actually you have CUDA 10 installed:

pip install tensorflow-gpu==2.0.0

output:

I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_100.dll

which was the solution for me.

How to submit a form with JavaScript by clicking a link?

You could give the form and the link some ids and then subscribe for the onclick event of the link and submit the form:

<form id="myform" action="" method="POST">
    <a href="#" id="mylink"> submit </a>
</form>

and then:

window.onload = function() {
    document.getElementById('mylink').onclick = function() {
        document.getElementById('myform').submit();
        return false;
    };
};

I would recommend you using a submit button for submitting forms as it respects the markup semantics and it will work even for users with javascript disabled.

How to get current user who's accessing an ASP.NET application?

The best practice is to check the Identity.IsAuthenticated Property first and then get the usr.UserName like this:

string userName = string.Empty;

if (System.Web.HttpContext.Current != null && 
    System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
    System.Web.Security.MembershipUser usr = Membership.GetUser();
    if (usr != null)
    {  
        userName = usr.UserName;
    }
}

Rollback one specific migration in Laravel

As stated in the Laravel manual, you may roll back specific number of migrations using the --step option

php artisan migrate:rollback --step=5

Turning multiple lines into one comma separated line

file

aaa
bbb
ccc
ddd

xargs

cat file | xargs

result

aaa bbb ccc ddd 

xargs improoved

cat file | xargs | sed -e 's/ /,/g'

result

aaa,bbb,ccc,ddd 

onChange and onSelect in DropDownList

I'd do it like this jsFiddle example.

JavaScript:

function check(elem) {
    document.getElementById('mySelect1').disabled = !elem.selectedIndex;
}

HTML:

<form>
<select id="mySelect" onChange="check(this);">
<option>No</option>
<option>Yes</option>
</select>

<select id="mySelect1" disabled="disabled" >
<option>Dep1</option>
<option>Dep2</option>
<option>Dep3</option>
<option>Dep4</option>
</select>
</form>

How to check if ZooKeeper is running or up from command prompt?

From a Windows 10

  • Open Command Promt then type telnet localhost 2181and then you type srvr OR
  • From inside bin folder, open a PowerShell window and type zkServer.sh status

Regular expression to limit number of characters to 10

/^[a-z]{0,10}$/ should work. /^[a-z]{1,10}$/ if you want to match at least one character, like /^[a-z]+$/ does.

How do I display todays date on SSRS report?

You can also drag and drop "Execution Time" item from Built-in Fields list.

How can I pass an Integer class correctly by reference?

You are correct here:

Integer i = 0;
i = i + 1;  // <- I think that this is somehow creating a new object!

First: Integer is immutable.

Second: the Integer class is not overriding the + operator, there is autounboxing and autoboxing involved at that line (In older versions of Java you would get an error on the above line).
When you write i + 1 the compiler first converts the Integer to an (primitive) int for performing the addition: autounboxing. Next, doing i = <some int> the compiler converts from int to an (new) Integer: autoboxing.
So + is actually being applied to primitive ints.

Best practice when adding whitespace in JSX

I tend to use &nbsp;

It's not pretty but it's the least confusing way to add whitespace I've found and it gives me absolute control over how much whitespace I add.

If I want to add 5 spaces:

Hello&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span className="second-word-formatting">World!</span>

It's easy to identify exactly what I'm trying to do here when I come back to the code weeks later.

function to remove duplicate characters in a string

/* program to remove the duplicate character in string */
/* Author senthilkumar M*/

char *dup_remove(char *str) 
{
    int i = 0, j = 0, l = strlen(str);
    int flag = 0, result = 0;

    for(i = 0; i < l; i++) {
         result = str[i] - 'a';
         if(flag & (1 << result)) {
            */* if duplicate found remove & shift the array*/*
            for(j = i; j < l; j++) {
                  str[j] = str[j+1];
             }
             i--; 
             l--; /* duplicates removed so string length reduced by 1 character*/
             continue;
         }
         flag |= (1 << result);
     }
     return str;
}

How do I "commit" changes in a git submodule?

Note that if you have committed a bunch of changes in various submodules, you can (or will be soon able to) push everything in one go (ie one push from the parent repo), with:

git push --recurse-submodules=on-demand

git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

--recurse-submodules=<check|on-demand|no>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.

When to use: Java 8+ interface default method, vs. abstract method

In Java 8, an interface looks like an abstract class although their might be some differences such as :

1) Abstract classes are classes, so they are not restricted to other restrictions of the interface in Java e.g. abstract class can have the state, but you cannot have the state on the interface in Java.

2) Another semantic difference between interface with default methods and abstract class is that you can define constructors inside an abstract class, but you cannot define constructor inside interface in Java

How do you sort an array on multiple columns?

Came across a need to do SQL-style mixed asc and desc object array sorts by keys.

kennebec's solution above helped me get to this:

Array.prototype.keySort = function(keys) {

keys = keys || {};

// via
// https://stackoverflow.com/questions/5223/length-of-javascript-object-ie-associative-array
var obLen = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key))
            size++;
    }
    return size;
};

// avoiding using Object.keys because I guess did it have IE8 issues?
// else var obIx = function(obj, ix){ return Object.keys(obj)[ix]; } or
// whatever
var obIx = function(obj, ix) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (size == ix)
                return key;
            size++;
        }
    }
    return false;
};

var keySort = function(a, b, d) {
    d = d !== null ? d : 1;
    // a = a.toLowerCase(); // this breaks numbers
    // b = b.toLowerCase();
    if (a == b)
        return 0;
    return a > b ? 1 * d : -1 * d;
};

var KL = obLen(keys);

if (!KL)
    return this.sort(keySort);

for ( var k in keys) {
    // asc unless desc or skip
    keys[k] = 
            keys[k] == 'desc' || keys[k] == -1  ? -1 
          : (keys[k] == 'skip' || keys[k] === 0 ? 0 
          : 1);
}

this.sort(function(a, b) {
    var sorted = 0, ix = 0;

    while (sorted === 0 && ix < KL) {
        var k = obIx(keys, ix);
        if (k) {
            var dir = keys[k];
            sorted = keySort(a[k], b[k], dir);
            ix++;
        }
    }
    return sorted;
});
return this;
};

sample usage:

var obja = [
  {USER:"bob",  SCORE:2000, TIME:32,    AGE:16, COUNTRY:"US"},
  {USER:"jane", SCORE:4000, TIME:35,    AGE:16, COUNTRY:"DE"},
  {USER:"tim",  SCORE:1000, TIME:30,    AGE:17, COUNTRY:"UK"},
  {USER:"mary", SCORE:1500, TIME:31,    AGE:19, COUNTRY:"PL"},
  {USER:"joe",  SCORE:2500, TIME:33,    AGE:18, COUNTRY:"US"},
  {USER:"sally",    SCORE:2000, TIME:30,    AGE:16, COUNTRY:"CA"},
  {USER:"yuri", SCORE:3000, TIME:34,    AGE:19, COUNTRY:"RU"},
  {USER:"anita",    SCORE:2500, TIME:32,    AGE:17, COUNTRY:"LV"},
  {USER:"mark", SCORE:2000, TIME:30,    AGE:18, COUNTRY:"DE"},
  {USER:"amy",  SCORE:1500, TIME:29,    AGE:19, COUNTRY:"UK"}
];

var sorto = {
  SCORE:"desc",TIME:"asc", AGE:"asc"
};

obja.keySort(sorto);

yields the following:

 0: {     USER: jane;     SCORE: 4000;    TIME: 35;       AGE: 16;    COUNTRY: DE;   }
 1: {     USER: yuri;     SCORE: 3000;    TIME: 34;       AGE: 19;    COUNTRY: RU;   }
 2: {     USER: anita;    SCORE: 2500;    TIME: 32;       AGE: 17;    COUNTRY: LV;   }
 3: {     USER: joe;      SCORE: 2500;    TIME: 33;       AGE: 18;    COUNTRY: US;   }
 4: {     USER: sally;    SCORE: 2000;    TIME: 30;       AGE: 16;    COUNTRY: CA;   }
 5: {     USER: mark;     SCORE: 2000;    TIME: 30;       AGE: 18;    COUNTRY: DE;   }
 6: {     USER: bob;      SCORE: 2000;    TIME: 32;       AGE: 16;    COUNTRY: US;   }
 7: {     USER: amy;      SCORE: 1500;    TIME: 29;       AGE: 19;    COUNTRY: UK;   }
 8: {     USER: mary;     SCORE: 1500;    TIME: 31;       AGE: 19;    COUNTRY: PL;   }
 9: {     USER: tim;      SCORE: 1000;    TIME: 30;       AGE: 17;    COUNTRY: UK;   }
 keySort: {  }

(using a print function from here)

here is a jsbin example.

edit: cleaned up and posted as mksort.js on github.

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

In AVD emulator how to see sdcard folder? and Install apk to AVD?

if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command

adb install apklocation.apk

How to make Toolbar transparent?

try below code

<android.support.design.widget.AppBarLayout
                    android:id="@+id/app_bar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:theme="@style/AppTheme.Transparent"
                    >
                        <android.support.v7.widget.Toolbar
                            android:id="@+id/toolbar"
                            android:layout_width="match_parent"
                            android:layout_height="?attr/actionBarSize"
                            app:popupTheme="@style/AppTheme.PopupOverlay" />
                </android.support.design.widget.AppBarLayout>

style.xml

<style name="AppTheme.Transparent" parent="ThemeOverlay.AppCompat.Light">
        <item name="colorPrimary">@android:color/transparent</item>
        <item name="colorControlActivated">@color/colorWhite</item>
        <item name="colorControlNormal">@color/colorWhite</item>
    </style>

c# write text on bitmap

Very old question, but just had to build this for an app today and found the settings shown in other answers do not result in a clean image (possibly as new options were added in later .Net versions).

Assuming you want the text in the centre of the bitmap, you can do this:

// Load the original image
Bitmap bmp = new Bitmap("filename.bmp");

// Create a rectangle for the entire bitmap
RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);

// Create graphic object that will draw onto the bitmap
Graphics g = Graphics.FromImage(bmp);

// ------------------------------------------
// Ensure the best possible quality rendering
// ------------------------------------------
// The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing). 
// One exception is that path gradient brushes do not obey the smoothing mode. 
// Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
g.SmoothingMode = SmoothingMode.AntiAlias;

// The interpolation mode determines how intermediate values between two endpoints are calculated.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;

// Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

// This one is important
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

// Create string formatting options (used for alignment)
StringFormat format = new StringFormat()
{
    Alignment = StringAlignment.Center,
    LineAlignment = StringAlignment.Center
};

// Draw the text onto the image
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf, format);

// Flush all graphics changes to the bitmap
g.Flush();

// Now save or use the bitmap
image.Image = bmp;

References

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

---- July 2019 ----

(using Spring Boot)

I was surprised that Spring Boot, with all it's Zero Configuration magic, doesn't provide an easy way to inspect or log a simple JSON response body with RestTemplate. I looked through the various answers and comments provided here, and am sharing my own distilled version of what (still) works and seems to me like a reasonable solution, given the current options (I'm using Spring Boot 2.1.6 with Gradle 4.4)

1. Using Fiddler as http proxy

This is actually quite an elegant solution, as it bypasses all the cumbersome efforts of creating your own interceptor or changing the underlying http client to apache (see below).

Install and run Fiddler

and then

add -DproxySet=true -Dhttp.proxyHost=localhost -Dhttp.proxyPort=8888 to your VM Options

2. Using Apache HttpClient

Add Apache HttpClient to your Maven or Gradle dependencies.

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.9</version>
</dependency>

Use HttpComponentsClientHttpRequestFactory as RequestFactory for RestTemplate. The simplest way to do that would be:

RestTemplate restTemplate = new RestTemplate();

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

Enable DEBUG in your application.properties file (if you're using Spring Boot)

logging.level.org.apache.http=DEBUG

If you're using Spring Boot, you'll need to make sure you have a logging framework set up, e.g. by using a spring-boot-starter dependency that includes spring-boot-starter-logging.

3. Use an Interceptor

I'll let you read through the proposals, counter-proposals, and gotchas in the other answers and comments and decide for yourself if you want to go down that path.

4. Log URL and Response Status without Body

Although this doesn't meet the stated requirements of logging the body, it's a quick and simple way to start logging your REST calls. It displays the full URL and response status.

Simply add the following line to your application.properties file (assuming you're using Spring Boot, and assuming you are using a spring boot starter dependency that includes spring-boot-starter-logging)

logging.level.org.springframework.web.client.RestTemplate=DEBUG

The output will look something like this:

2019-07-29 11:53:50.265 DEBUG o.s.web.client.RestTemplate : HTTP GET http://www.myrestservice.com/Endpoint?myQueryParam=myValue
2019-07-29 11:53:50.276 DEBUG o.s.web.client.RestTemplate : Accept=[application/json]
2019-07-29 11:53:50.584 DEBUG o.s.web.client.RestTemplate : Response 200 OK
2019-07-29 11:53:50.585 DEBUG o.s.web.client.RestTemplate : Reading to [org.mynamespace.MyJsonModelClass]

Mongoose, Select a specific field with find

Exclude

Below code will retrieve all fields other than password within each document:

const users = await UserModel.find({}, {
  password: 0 
});
console.log(users);

Output

[
  {
    "_id": "5dd3fb12b40da214026e0658",
    "email": "[email protected]"
  }
]

Include

Below code will only retrieve email field within each document:

const users = await UserModel.find({}, {
  email: 1
});
console.log(users);

Output

[
  {
    "email": "[email protected]"
  }
]

how to sort order of LEFT JOIN in SQL query?

Try using MAX with a GROUP BY.

SELECT u.userName, MAX(c.carPrice)
FROM users u
    LEFT JOIN cars c ON u.id = c.belongsToUser
WHERE u.id = 4;
GROUP BY u.userName;

Further information on GROUP BY

The group by clause is used to split the selected records into groups based on unique combinations of the group by columns. This then allows us to use aggregate functions (eg. MAX, MIN, SUM, AVG, ...) that will be applied to each group of records in turn. The database will return a single result record for each grouping.

For example, if we have a set of records representing temperatures over time and location in a table like this:

Location   Time    Temperature
--------   ----    -----------
London     12:00          10.0
Bristol    12:00          12.0
Glasgow    12:00           5.0
London     13:00          14.0
Bristol    13:00          13.0
Glasgow    13:00           7.0
...

Then if we want to find the maximum temperature by location, then we need to split the temperature records into groupings, where each record in a particular group has the same location. We then want to find the maximum temperature of each group. The query to do this would be as follows:

SELECT Location, MAX(Temperature)
FROM Temperatures
GROUP BY Location;

Column calculated from another column?

If it is a selection, you can do it as:

SELECT id, value, (value/2) AS calculated FROM mytable

Else, you can also first alter the table to add the missing column and then do an UPDATE query to compute the values for the new column as:

UPDATE mytable SET calculated = value/2;

If it must be automatic, and your MySQL version allows it, you can try with triggers

How do you make Vim unhighlight what you searched for?

/lkjasdf has always been faster than :noh for me.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

In your app/config/parameters.yml

# This file is auto-generated during the composer install
parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: 3306
    database_name: symfony
    database_user: root
    database_password: "your_password"
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: en
    secret: ThisTokenIsNotSoSecretChangeIt

The value of database_password should be within double or single quotes as in: "your_password" or 'your_password'.

I have seen most of users experiencing this error because they are using password with leading zero or numeric values.

Run JavaScript in Visual Studio Code

Follow these steps in VS code.[performed in windows os]

  1. Create new file

  2. Write javascript codes in it

  3. Save file as filename.js

  4. Go to Debugging menu

  5. Click on Start debugging

  6. or simply press F5

screenshot of starting debugging

screenshot of output of js code in terminal

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

php string to int

What do you even want the result to be? 888888? If so, just remove the spaces with str_replace, then convert.

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

Convert ASCII TO UTF-8 Encoding

Using iconv looks like best solution but i my case I have Notice form this function: "Detected an illegal character in input string in" (without igonore). I use 2 functions to manipulate ASCII strings convert it to array of ASCII code and then serialize:

public static function ToAscii($string) {
    $strlen = strlen($string);
    $charCode = array();
    for ($i = 0; $i < $strlen; $i++) {
        $charCode[] = ord(substr($string, $i, 1));
    }
    $result = json_encode($charCode);
    return $result;
}

public static function fromAscii($string) {
    $charCode = json_decode($string);
    $result = '';
    foreach ($charCode as $code) {
        $result .= chr($code);
    };
    return $result;
}

Bootstrap 3 Navbar Collapse

I think I found a simple solution to changing the collapse breakpoint, only through css.

I hope others can confirm it since I didn't test it thoroughly and I'm not sure if there are side effects to this solution.

You have to change the media query values for the following class definitions:

@media (min-width: BREAKPOINT px ){
    .navbar-toggle{display:none}
}

@media (min-width: BREAKPOINT px){
    .navbar-collapse{
        width:auto;
        border-top:0;box-shadow:none
    }
    .navbar-collapse.collapse{
        display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important
    }
    .navbar-collapse.in{
        overflow-y:visible
   }
   .navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{
        padding-left:0;padding-right:0
    }
}

This is what worked for me on my current project, but I still need to change some css definitions to arrange the menu properly for all screen sizes.

Hope this helps.

conversion from infix to prefix

This algorithm will help you for better understanding .

Step 1. Push “)” onto STACK, and add “(“ to end of the A.

Step 2. Scan A from right to left and repeat step 3 to 6 for each element of A until the STACK is empty.

Step 3. If an operand is encountered add it to B.

Step 4. If a right parenthesis is encountered push it onto STACK.

Step 5. If an operator is encountered then: a. Repeatedly pop from STACK and add to B each operator (on the top of STACK) which has same or higher precedence than the operator. b. Add operator to STACK.

Step 6. If left parenthesis is encontered then a. Repeatedly pop from the STACK and add to B (each operator on top of stack until a left parenthesis is encounterd) b. Remove the left parenthesis.

Step 7. Exit

Characters allowed in GET parameter

All of the rules concerning the encoding of URIs (which contains URNs and URLs) are specified in the RFC1738 and the RFC3986, here's a TL;DR of these long and boring documents:

Percent-encoding, also known as URL encoding, is a mechanism for encoding information in a URI under certain circumstances. The characters allowed in a URI are either reserved or unreserved. Reserved characters are those characters that sometimes have special meaning, but they are not the only characters that needs encoding.

There are 66 unreserved characters that doesn't need any encoding: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~

There are 18 reserved characters which needs to be encoded: !*'();:@&=+$,/?#[], and all the other characters must be encoded.

To percent-encode a character, simply concatenate "%" and its ASCII value in hexadecimal. The php functions "urlencode" and "rawurlencode" do this job for you.

What are the differences between B trees and B+ trees?

B+Trees are much easier and higher performing to do a full scan, as in look at every piece of data that the tree indexes, since the terminal nodes form a linked list. To do a full scan with a B-Tree you need to do a full tree traversal to find all the data.

B-Trees on the other hand can be faster when you do a seek (looking for a specific piece of data by key) especially when the tree resides in RAM or other non-block storage. Since you can elevate commonly used nodes in the tree there are less comparisons required to get to the data.

sql query to get earliest date

If you just want the date:

SELECT MIN(date) as EarliestDate
FROM YourTable
WHERE id = 2

If you want all of the information:

SELECT TOP 1 id, name, score, date
FROM YourTable
WHERE id = 2
ORDER BY Date

Prevent loops when you can. Loops often lead to cursors, and cursors are almost never necessary and very often really inefficient.

Converting a String to Object

String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

String s = "Hi";

Object a =s;

href="javascript:" vs. href="javascript:void(0)"

I usually do not use any href and change the aspect with css, making them seems link. Thus you do not have to worry about link effect at all, except for the event handler of your application

a {
  text-recoration: underline;
  cursor: pointer;
}

Disabling same-origin policy in Safari

Later versions of Safari allow you to Disable Cross-Origin Restrictions. Just enable the developer menu from Preferences >> Advanced, and select "Disable Cross-Origin Restrictions" from the develop menu.

If you want local only, then you only need to enable the developer menu, and select "Disable local file restrictions" from the develop menu.

How to preview selected image in input type="file" in popup using jQuery?

Just check my scripts it's working well:

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
#list img{
  width: auto;
  height: 100px;
  margin: 10px ;
}

'tuple' object does not support item assignment

A tuple is immutable and thus you get the error you posted.

>>> pixels = [1, 2, 3]
>>> pixels[0] = 5
>>> pixels = (1, 2, 3)
>>> pixels[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

In your specific case, as correctly pointed out in other answers, you should write:

pixel = (pixel[0] + 20, pixel[1], pixel[2])

Find an element in a list of tuples

Or takewhile, ( addition to this, example of more values is shown ):

>>> a= [(1,2),(1,4),(3,5),(5,7),(0,2)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,a))
[(1, 2), (1, 4)]
>>> 

if unsorted, like:

>>> a= [(1,2),(3,5),(1,4),(5,7)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,sorted(a,key=lambda x: x[0]==1)))
[(1, 2), (1, 4)]
>>> 

How can you get the first digit in an int (C#)?

An obvious, but slow, mathematical approach is:

int firstDigit = (int)(i / Math.Pow(10, (int)Math.Log10(i))));

Exception is never thrown in body of corresponding try statement

As pointed out in the comments, you cannot catch an exception that's not thrown by the code within your try block. Try changing your code to:

try{
    Integer.parseInt(args[i-1]); // this only throws a NumberFormatException
}
catch(NumberFormatException e){
    throw new MojException("Bledne dane");
}

Always check the documentation to see what exceptions are thrown by each method. You may also wish to read up on the subject of checked vs unchecked exceptions before that causes you any confusion in the future.

Found a swap file by the name

More info... Some times .swp files might be holded by vm that was running in backgroung. You may see permission denied message when try to delete the files.

Check and kill process vm

Android. Fragment getActivity() sometimes returns null

The best to get rid of this is to keep activity reference when onAttach is called and use the activity reference wherever needed, for e.g.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

Edited, since onAttach(Activity) is depreciated & now onAttach(Context) is being used

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

TL;DR

You are missing the @Id entity property, and that's why Hibernate is throwing that exception.

Entity identifiers

Any JPA entity must have an identifier property, that is marked with the Id annotation.

There are two types of identifiers:

  • assigned
  • auto-generated

Assigned identifiers

An assigned identifier looks as follows:

@Id
private Long id;

Notice that we are using a wrapper (e.g., Long, Integer) instead of a primitive type (e.g., long, int). Using a wrapper type is a better choice when using Hibernate because, by checking if the id is null or not, Hibernate can better determine if an entity is transient (it does not have an associated table row) or detached (it has an associated table row, but it's not managed by the current Persistence Context).

The assigned identifier must be set manually by the application prior to calling persist:

Post post = new Post();
post.setId(1L);

entityManager.persist(post);

Auto-generated identifiers

An auto-generated identifier requires the @GeneratedValue annotation besides the @Id:

@Id
@GeneratedValue
private int id;

There are 3 strategies Hibernate can use to auto-generate the entity identifier:

  • IDENTITY
  • SEQUENCE
  • TABLE

The IDENTITY strategy is to be avoided if the underlying database supports sequences (e.g., Oracle, PostgreSQL, MariaDB since 10.3, SQL Server since 2012). The only major database that does not support sequences is MySQL.

The problem with IDENTITY is that automatic Hibernate batch inserts are disabled for this strategy.

The SEQUENCE strategy is the best choice unless you are using MySQL. For the SEQUENCE strategy, you also want to use the pooled optimizer to reduce the number of database roundtrips when persisting multiple entities in the same Persistence Context.

The TABLE generator is a terrible choice because it does not scale. For portability, you are better off using SEQUENCE by default and switch to IDENTITY for MySQL only.

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

Authentication issue when debugging in VS2013 - iis express

F4 doesn't always bring me to this panel. Besides, it is often said that a picture is worth a thousand words.

enter image description here

Making a cURL call in C#

Below is a working example code.

Please note you need to add a reference to Newtonsoft.Json.Linq

string url = "https://yourAPIurl";
WebRequest myReq = WebRequest.Create(url);
string credentials = "xxxxxxxxxxxxxxxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
CredentialCache mycache = new CredentialCache();
myReq.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
var json = "[" + content + "]"; // change this to array
var objects = JArray.Parse(json); // parse as array  
foreach (JObject o in objects.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = p.Value.ToString();
        Console.Write(name + ": " + value);
    }
}
Console.ReadLine();

Reference: TheDeveloperBlog.com

Easy way to prevent Heroku idling?

Tested and working on my own Heroku app using Node.js 0.10.x on 6/28/2013

var http = require('http'); //importing http

function startKeepAlive() {
    setInterval(function() {
        var options = {
            host: 'your_app_name.herokuapp.com',
            port: 80,
            path: '/'
        };
        http.get(options, function(res) {
            res.on('data', function(chunk) {
                try {
                    // optional logging... disable after it's working
                    console.log("HEROKU RESPONSE: " + chunk);
                } catch (err) {
                    console.log(err.message);
                }
            });
        }).on('error', function(err) {
            console.log("Error: " + err.message);
        });
    }, 20 * 60 * 1000); // load every 20 minutes
}

startKeepAlive();

.NET code to send ZPL to Zebra printers

This way you will be able to send ZPL to a printer no matter how it is connected (LPT, USB, Network Share...)

Create the RawPrinterHelper class (from the Microsoft article on How to send raw data to a printer by using Visual C# .NET):

using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class RawPrinterHelper
{
    // Structure and API declarions:
    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)] public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)] public string pDataType;
    }
    [DllImport("winspool.Drv", EntryPoint="OpenPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

    [DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="StartDocPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool StartDocPrinter( IntPtr hPrinter, Int32 level,  [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

    [DllImport("winspool.Drv", EntryPoint="EndDocPrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="StartPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="EndPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten );

    // SendBytesToPrinter()
    // When the function is given a printer name and an unmanaged array
    // of bytes, the function sends those bytes to the print queue.
    // Returns true on success, false on failure.
    public static bool SendBytesToPrinter( string szPrinterName, IntPtr pBytes, Int32 dwCount)
    {
        Int32    dwError = 0, dwWritten = 0;
        IntPtr    hPrinter = new IntPtr(0);
        DOCINFOA    di = new DOCINFOA();
        bool    bSuccess = false; // Assume failure unless you specifically succeed.

        di.pDocName = "My C#.NET RAW Document";
        di.pDataType = "RAW";

        // Open the printer.
        if( OpenPrinter( szPrinterName.Normalize(), out hPrinter, IntPtr.Zero ) )
        {
            // Start a document.
            if( StartDocPrinter(hPrinter, 1, di) )
            {
                // Start a page.
                if( StartPagePrinter(hPrinter) )
                {
                    // Write your bytes.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        // If you did not succeed, GetLastError may give more information
        // about why not.
        if( bSuccess == false )
        {
                dwError = Marshal.GetLastWin32Error();
        }
        return bSuccess;
    }

    public static bool SendFileToPrinter( string szPrinterName, string szFileName )
    {
        // Open the file.
        FileStream fs = new FileStream(szFileName, FileMode.Open);
        // Create a BinaryReader on the file.
        BinaryReader br = new BinaryReader(fs);
        // Dim an array of bytes big enough to hold the file's contents.
        Byte []bytes = new Byte[fs.Length];
        bool bSuccess = false;
        // Your unmanaged pointer.
        IntPtr pUnmanagedBytes = new IntPtr(0);
        int nLength;

        nLength = Convert.ToInt32(fs.Length);
        // Read the contents of the file into the array.
        bytes = br.ReadBytes( nLength );
        // Allocate some unmanaged memory for those bytes.
        pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
        // Copy the managed byte array into the unmanaged array.
        Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
        // Send the unmanaged bytes to the printer.
        bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
        // Free the unmanaged memory that you allocated earlier.
        Marshal.FreeCoTaskMem(pUnmanagedBytes);
        return bSuccess;
    }
    public static bool SendStringToPrinter( string szPrinterName, string szString )
    {
        IntPtr pBytes;
        Int32 dwCount;
        // How many characters are in the string?
        dwCount = szString.Length;
        // Assume that the printer is expecting ANSI text, and then convert
        // the string to ANSI text.
        pBytes = Marshal.StringToCoTaskMemAnsi(szString);
        // Send the converted ANSI string to the printer.
        SendBytesToPrinter(szPrinterName, pBytes, dwCount);
        Marshal.FreeCoTaskMem(pBytes);
        return true;
    }
}

Call the print method:

private void BtnPrint_Click(object sender, System.EventArgs e)
{
    string s = "^XA^LH30,30\n^FO20,10^ADN,90,50^AD^FDHello World^FS\n^XZ";

    PrintDialog pd  = new PrintDialog();
    pd.PrinterSettings = new PrinterSettings();
    if(DialogResult.OK == pd.ShowDialog(this))
    {
        RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);
    }
}

There are 2 gotchas I've come across that happen when you're sending txt files with ZPL codes to the printer:

  1. The file has to end with a new line character
  2. Encoding has to be set to Encoding.Default when reading ANSI txt files with special characters

    public static bool SendTextFileToPrinter(string szFileName, string printerName)
    {
        var sb = new StringBuilder();
    
        using (var sr = new StreamReader(szFileName, Encoding.Default))
        {
            while (!sr.EndOfStream)
            {
                sb.AppendLine(sr.ReadLine());
            }
        }
    
        return RawPrinterHelper.SendStringToPrinter(printerName, sb.ToString());
    }
    

How do I get some variable from another class in Java?

Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.

Reactive forms - disabled attribute

in Angular-9 if you want to disable/enable on button click here is a simple solution if you are using reactive forms.

define a function in component.ts file

//enable example you can use the same approach for disable with .disable()

toggleEnable() {
  this.yourFormName.controls.formFieldName.enable();
  console.log("Clicked")
} 

Call it from your component.html

e.g

<button type="button" data-toggle="form-control" class="bg-primary text-white btn- 
                reset" style="width:100%"(click)="toggleEnable()">

Getting output of system() calls in Ruby

puts `date`
puts $?


Mon Mar  7 19:01:15 PST 2016
pid 13093 exit 0

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

General sibling combinator

The general sibling combinator selector is very similar to the adjacent sibling combinator selector. The difference is that the element being selected doesn't need to immediately succeed the first element, but can appear anywhere after it.

More info

SVN Commit specific files

You basically put the files you want to commit on the command line

svn ci file1 file2 dir1/file3

Recursive Fibonacci

By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1. Therefore, you should handle it.

#include <iostream>
using namespace std;

int Fibonacci(int);

int main(void) {
    int number;

    cout << "Please enter a positive integer: ";
    cin >> number;
    if (number < 0)
        cout << "That is not a positive integer.\n";
    else
        cout << number << " Fibonacci is: " << Fibonacci(number) << endl;
}

int Fibonacci(int x) 
{
    if (x < 2){
     return x;
    }     
    return (Fibonacci (x - 1) + Fibonacci (x - 2));
}

How do you extract a column from a multi-dimensional array?

If you want to grab more than just one column just use slice:

 a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
    print(a[:, [1, 2]])
[[2 3]
[5 6]
[8 9]]

Checking if float is an integer

stdlib float modf (float x, float *ipart) splits into two parts, check if return value (fractional part) == 0.

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

How to set textColor of UILabel in Swift

This code example that follows shows a basic UILabel configuration.

let lbl = UILabel(frame: CGRectMake(0, 0, 300, 200))
lbl.text = "yourString"

// Enum type, two variations:
lbl.textAlignment = NSTextAlignment.Right
lbl.textAlignment = .Right

lbl.textColor = UIColor.red
lbl.shadowColor = UIColor.black
lbl.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(lbl)

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

Simply switch to the Design View, and locate the concerned widget. Grab the one of the dots on the boundary of the widget and join it to an appropriate edge of the screen (or to a dot on some other widget).

For instance, if the widget is a toolbar, just grab the top-most dot and join it to the top-most edge of the phone screen as shown in the image.

Design View

No Access-Control-Allow-Origin header is present on the requested resource

Solution:
Instead of using setHeader method I have used addHeader.

response.addHeader("Access-Control-Allow-Origin", "*");

* in above line will allow access to all domains, For allowing access to specific domain only:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");

For issues related to IE<=9, Please see here.

Is it possible to use argsort in descending order?

Instead of using np.argsort you could use np.argpartition - if you only need the indices of the lowest/highest n elements.

That doesn't require to sort the whole array but just the part that you need but note that the "order inside your partition" is undefined, so while it gives the correct indices they might not be correctly ordered:

>>> avgDists = [1, 8, 6, 9, 4]
>>> np.array(avgDists).argpartition(2)[:2]  # indices of lowest 2 items
array([0, 4], dtype=int64)

>>> np.array(avgDists).argpartition(-2)[-2:]  # indices of highest 2 items
array([1, 3], dtype=int64)

Array versus linked-list

First of all, in C++ linked-lists shouldn't be much more trouble to work with than an array. You can use the std::list or the boost pointer list for linked lists. The key issues with linked lists vs arrays are extra space required for pointers and terrible random access. You should use a linked list if you

  • you don't need random access to the data
  • you will be adding/deleting elements, especially in the middle of the list

rand() returns the same number each time the program is run

You need to change the seed.

int main() {

    srand(time(NULL));
    cout << (rand() % 101);
    return 0;
}

the srand seeding thing is true also for a c language code.


See also: http://xkcd.com/221/

Typescript - multidimensional array initialization

You only need [] to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.

The same thing applies at the first level in your loop. It is merely an array and [] is a new empty array - job done.

As for the second level, if Thing is a class then new Thing() will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.

class Something {
    private things: Thing[][];

    constructor() {
        this.things = [];

        for(var i: number = 0; i < 10; i++) {
            this.things[i] = [];
            for(var j: number = 0; j< 10; j++) {
                this.things[i][j] = new Thing();
            }
        }
    }
}

What is the use of a private static variable in Java?

private static variable will be shared in subclass as well. If you changed in one subclass and the other subclass will get the changed value, in which case, it may not what you expect.

public class PrivateStatic {

private static int var = 10;
public void setVar(int newVal) {
    var = newVal;
}

public int getVar() {
    return var;
}

public static void main(String... args) {
    PrivateStatic p1 = new Sub1();
    System.out.println(PrivateStatic.var);
    p1.setVar(200);

    PrivateStatic p2 = new Sub2();
    System.out.println(p2.getVar());
}
}


class Sub1 extends PrivateStatic {

}

class Sub2 extends PrivateStatic {
}

Google Chromecast sender error if Chromecast extension is not installed or using incognito

Update: After several attempts, it looks like this may have been fixed in latest Chrome builds (per Paul Irish's comment below). That would suggest we will see this fixed in stable Chrome June-July 2016. Let's see ...

This is a known bug with the official Chromecast JavaScript library. Instead of failing silently, it dumps these error messages in all non-Chrome browsers as well as Chrome browsers where the Chromecast extension isn't present.

The Chromecast team have indicated they won't fix this bug.

If you are a developer shipping with this library, you can't do anything about it according to Chromecast team. You can only inform users to ignore the errors. (I believe Chromecast team is not entirely correct as the library could, at the least, avoid requesting the extension scipt if the browser is not Chrome. And I suspect it could be possible to suppress the error even if it is Chrome, but haven't tried anything.)

If you are a user annoyed by these console messages, you can switch to Chrome if not using it already. Within Chrome, either:

Update [Nov 13, 2014]: The problem has now been acknowledged by Google. A member of the Chromecast team seems to suggest the issue will be bypassed by a change the team is currently working on.

Update 2 [Feb 17, 2015]: The team claim there's nothing they can do to remove the error logs as it's a standard Chrome network error and they are still working on a long-term fix. Public comments on the bug tracker were closed with that update.

Update 3 [Dec 4, 2015]: This has finally been fixed! In the end, Chrome team simply added some code to block out this specific error. Hopefully some combination of devtools and extensions API will be improved in the future to make it possible to fix this kind of problem without patching the browser. Chrome Canary already has the patch, so it should roll out to all users around mid-January. Additionally, the team has confirmed the issue no longer affects other browsers as the SDK was updated to only activate if it's in Chrome.

Update 4 (April 30): Nope, not yet anyway. Thankfully Google's developer relations team are more aware than certain other stakeholders how badly this has affected developer experience. More whitelist updates have recently been made to clobber these log messages. Current status at top of the post.

Handling null values in Freemarker

Use ?? operator at the end of your <#if> statement.

This example demonstrates how to handle null values for two lists in a Freemaker template.

List of cars:
<#if cars??>
    <#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
    <#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>

const to Non-const Conversion in C++

You can assign a const object to a non-const object just fine. Because you're copying and thus creating a new object, constness is not violated.

Like so:

int main() {
   const int a = 3;
   int b = a;
}

It's different if you want to obtain a pointer or reference to the original, const object:

int main() {
   const int a = 3;
   int& b = a;       // or int* b = &a;
}

//  error: invalid initialization of reference of type 'int&' from
//         expression of type 'const int'

You can use const_cast to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a through b in the below example:

int main() {
   const int a = 3;
   int& b = const_cast<int&>(a);

   b = 3;
}

Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.

If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.

Default port for SQL Server

SQL Server default port is 1434.

To allow remote access I had to release those ports on my firewall:

Protocol  |   Port
---------------------
UDP       |   1050
TCP       |   1050
TCP       |   1433
UDP       |   1434

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

For your code

var mytextvalue = document.getElementById("mytext");

mytextvalue will contain null if you have a document.write() statement before this code. So remove the document.write statement and you should get a proper text object in the variable mytextvalue.

This is caused by document.write changing the document.

Append text to textarea with javascript

Use event delegation by assigning the onclick to the <ol>. Then pass the event object as the argument, and using that, grab the text from the clicked element.

_x000D_
_x000D_
function addText(event) {_x000D_
    var targ = event.target || event.srcElement;_x000D_
    document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
  <li>Hello</li>_x000D_
  <li>World</li>_x000D_
  <li>Earthlings</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Note that this method of passing the event object works in older IE as well as W3 compliant systems.

Ruby on Rails: How do I add placeholder text to a f.text_field?

In Rails 4(Using HAML):

=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'

Select Tag Helper in ASP.NET Core MVC

Using the Select Tag helpers to render a SELECT element

In your GET action, create an object of your view model, load the EmployeeList collection property and send that to the view.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.EmployeesList = new List<Employee>
    {
        new Employee { Id = 1, FullName = "Shyju" },
        new Employee { Id = 2, FullName = "Bryan" }
    };
    return View(vm);
}

And in your create view, create a new SelectList object from the EmployeeList property and pass that as value for the asp-items property.

@model MyViewModel
<form asp-controller="Home" asp-action="Create">

    <select asp-for="EmployeeId" 
            asp-items="@(new SelectList(Model.EmployeesList,"Id","FullName"))">
        <option>Please select one</option>
    </select>

    <input type="submit"/>

</form>

And your HttpPost action method to accept the submitted form data.

[HttpPost]
public IActionResult Create(MyViewModel model)
{
   //  check model.EmployeeId 
   //  to do : Save and redirect
}

Or

If your view model has a List<SelectListItem> as the property for your dropdown items.

public class MyViewModel
{
    public int EmployeeId { get; set; }
    public string Comments { get; set; }
    public List<SelectListItem> Employees { set; get; }
}

And in your get action,

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "1"},
        new SelectListItem {Text = "Sean", Value = "2"}
    };
    return View(vm);
}

And in the view, you can directly use the Employees property for the asp-items.

@model MyViewModel
<form asp-controller="Home" asp-action="Create">

    <label>Comments</label>
    <input type="text" asp-for="Comments"/>

    <label>Lucky Employee</label>
    <select asp-for="EmployeeId" asp-items="@Model.Employees" >
        <option>Please select one</option>
    </select>

    <input type="submit"/>

</form>

The class SelectListItem belongs to Microsoft.AspNet.Mvc.Rendering namespace.

Make sure you are using an explicit closing tag for the select element. If you use the self closing tag approach, the tag helper will render an empty SELECT element!

The below approach will not work

<select asp-for="EmployeeId" asp-items="@Model.Employees" />

But this will work.

<select asp-for="EmployeeId" asp-items="@Model.Employees"></select>

Getting data from your database table using entity framework

The above examples are using hard coded items for the options. So i thought i will add some sample code to get data using Entity framework as a lot of people use that.

Let's assume your DbContext object has a property called Employees, which is of type DbSet<Employee> where the Employee entity class has an Id and Name property like this

public class Employee
{
   public int Id { set; get; }
   public string Name { set; get; }
}

You can use a LINQ query to get the employees and use the Select method in your LINQ expression to create a list of SelectListItem objects for each employee.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = context.Employees
                          .Select(a => new SelectListItem() {  
                              Value = a.Id.ToString(),
                              Text = a.Name
                          })
                          .ToList();
    return View(vm);
}

Assuming context is your db context object. The view code is same as above.

Using SelectList

Some people prefer to use SelectList class to hold the items needed to render the options.

public class MyViewModel
{
    public int EmployeeId { get; set; }
    public SelectList Employees { set; get; }
}

Now in your GET action, you can use the SelectList constructor to populate the Employees property of the view model. Make sure you are specifying the dataValueField and dataTextField parameters.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = new SelectList(GetEmployees(),"Id","FirstName");
    return View(vm);
}
public IEnumerable<Employee> GetEmployees()
{
    // hard coded list for demo. 
    // You may replace with real data from database to create Employee objects
    return new List<Employee>
    {
        new Employee { Id = 1, FirstName = "Shyju" },
        new Employee { Id = 2, FirstName = "Bryan" }
    };
}

Here I am calling the GetEmployees method to get a list of Employee objects, each with an Id and FirstName property and I use those properties as DataValueField and DataTextField of the SelectList object we created. You can change the hardcoded list to a code which reads data from a database table.

The view code will be same.

<select asp-for="EmployeeId" asp-items="@Model.Employees" >
    <option>Please select one</option>
</select>

Render a SELECT element from a list of strings.

Sometimes you might want to render a select element from a list of strings. In that case, you can use the SelectList constructor which only takes IEnumerable<T>

var vm = new MyViewModel();
var items = new List<string> {"Monday", "Tuesday", "Wednesday"};
vm.Employees = new SelectList(items);
return View(vm);

The view code will be same.

Setting selected options

Some times,you might want to set one option as the default option in the SELECT element (For example, in an edit screen, you want to load the previously saved option value). To do that, you may simply set the EmployeeId property value to the value of the option you want to be selected.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "11"},
        new SelectListItem {Text = "Tom", Value = "12"},
        new SelectListItem {Text = "Jerry", Value = "13"}
    };
    vm.EmployeeId = 12;  // Here you set the value
    return View(vm);
}

This will select the option Tom in the select element when the page is rendered.

Multi select dropdown

If you want to render a multi select dropdown, you can simply change your view model property which you use for asp-for attribute in your view to an array type.

public class MyViewModel
{
    public int[] EmployeeIds { get; set; }
    public List<SelectListItem> Employees { set; get; }
}

This will render the HTML markup for the select element with the multiple attribute which will allow the user to select multiple options.

@model MyViewModel
<select id="EmployeeIds" multiple="multiple" name="EmployeeIds">
    <option>Please select one</option>
    <option value="1">Shyju</option>
    <option value="2">Sean</option>
</select>

Setting selected options in multi select

Similar to single select, set the EmployeeIds property value to the an array of values you want.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "11"},
        new SelectListItem {Text = "Tom", Value = "12"},
        new SelectListItem {Text = "Jerry", Value = "13"}
    };
    vm.EmployeeIds= new int[] { 12,13} ;  
    return View(vm);
}

This will select the option Tom and Jerry in the multi select element when the page is rendered.

Using ViewBag to transfer the list of items

If you do not prefer to keep a collection type property to pass the list of options to the view, you can use the dynamic ViewBag to do so.(This is not my personally recommended approach as viewbag is dynamic and your code is prone to uncatched typo errors)

public IActionResult Create()
{       
    ViewBag.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "1"},
        new SelectListItem {Text = "Sean", Value = "2"}
    };
    return View(new MyViewModel());
}

and in the view

<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
    <option>Please select one</option>
</select>

Using ViewBag to transfer the list of items and setting selected option

It is same as above. All you have to do is, set the property (for which you are binding the dropdown for) value to the value of the option you want to be selected.

public IActionResult Create()
{       
    ViewBag.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "1"},
        new SelectListItem {Text = "Bryan", Value = "2"},
        new SelectListItem {Text = "Sean", Value = "3"}
    };

    vm.EmployeeId = 2;  // This will set Bryan as selected

    return View(new MyViewModel());
}

and in the view

<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
    <option>Please select one</option>
</select>

Grouping items

The select tag helper method supports grouping options in a dropdown. All you have to do is, specify the Group property value of each SelectListItem in your action method.

public IActionResult Create()
{
    var vm = new MyViewModel();

    var group1 = new SelectListGroup { Name = "Dev Team" };
    var group2 = new SelectListGroup { Name = "QA Team" };

    var employeeList = new List<SelectListItem>()
    {
        new SelectListItem() { Value = "1", Text = "Shyju", Group = group1 },
        new SelectListItem() { Value = "2", Text = "Bryan", Group = group1 },
        new SelectListItem() { Value = "3", Text = "Kevin", Group = group2 },
        new SelectListItem() { Value = "4", Text = "Alex", Group = group2 }
    };
    vm.Employees = employeeList;
    return View(vm);
}

There is no change in the view code. the select tag helper will now render the options inside 2 optgroup items.

Dialog to pick image from gallery or from camera

The code below can be used for taking a photo and for picking a photo. Just show a dialog with two options and upon selection, use the appropriate code.

To take picture from camera:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code (called requestCode)

To pick photo from gallery:

Intent pickPhoto = new Intent(Intent.ACTION_PICK,
           android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code

onActivityResult code:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
    switch(requestCode) {
    case 0:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }

    break; 
    case 1:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            imageview.setImageURI(selectedImage);
        }
    break;
    }
}

Finally add this permission in the manifest file:

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

Local Storage vs Cookies

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.

If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

You'll want to leave your session cookie as a cookie either way though.

As per the technical difference, and also my understanding:

  1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domainSO Question also mentions it.

  2. localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.

Assign one struct to another in C

Yes, assignment is supported for structs. However, there are problems:

struct S {
   char * p;
};

struct S s1, s2;
s1.p = malloc(100);
s2 = s1;

Now the pointers of both structs point to the same block of memory - the compiler does not copy the pointed to data. It is now difficult to know which struct instance owns the data. This is why C++ invented the concept of user-definable assignment operators - you can write specific code to handle this case.

video as site background? HTML 5

I might have a solution for the video as background, stretched to the browser-width or height, (but the video will still preserve the aspect ratio, couldnt find a solution for that yet.):

Put the video right after the body-tag with style="width:100%;". Right afterwords, put a "bodydummy"-tag:

<body>
<video id="bgVideo" autoplay poster="videos/poster.png">
    <source src="videos/test-h264-640x368-highqual-winff.mp4" type="video/mp4"/>
    <source src="videos/test-640x368-webmvp8-miro.webm" type="video/webm"/>
    <source src="videos/test-640x368-theora-miro.ogv" type="video/ogg"/>    
</video>

<img id="bgImg" src="videos/poster.png" />

<!-- This image stretches exactly to the browser width/height and lies behind the video-->

<div id="bodyDummy">

Put all your content inside the bodydummy-div and put the z-indexes correctly in CSS like this:

#bgImg{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
}

#bgVideo{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
}

#bodyDummy{ 
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    overflow: auto;
    width: 100%;
    height: 100%;
}

Hope I could help. Let me know when you could find a solution that the video does not maintain the aspect ratio, so it could fill the whole browser window so we do not have to put a bgimage.

JS regex: replace all digits in string

Use

s.replace(/\d/g, "X")

which will replace all occurrences. The g means global match and thus will not stop matching after the first occurrence.

Or to stay with your RegExp constructor:

s.replace(new RegExp("\\d", "g"), "X")

How do I check if a file exists in Java?

There are multiple ways to achieve this.

  1. In case of just for existence. It could be file or a directory.

    new File("/path/to/file").exists();
    
  2. Check for file

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isFile()) {}
    
  3. Check for Directory.

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isDirectory()) {}
    
  4. Java 7 way.

    Path path = Paths.get("/path/to/file");
    Files.exists(path)  // Existence 
    Files.isDirectory(path)  // is Directory
    Files.isRegularFile(path)  // Regular file 
    Files.isSymbolicLink(path)  // Symbolic Link
    

How to display a date as iso 8601 format with PHP

The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:

// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z

// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z

// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z

//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

Phone number validation Android

You shouldn't be using Regular Expressions when validating phone numbers. Check out this JSON API - numverify.com - it's free for a nunver if calls a month and capable of checking any phone number. Plus, each request comes with location, line type and carrier information.

Save PHP array to MySQL?

Serialize/Unserialize array for storage in a DB

Visit http://php.net/manual/en/function.serialize.php

From the PHP Manual:

Look under "Return" on the page

Returns a string containing a byte-stream representation of value that can be stored anywhere.

Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.

Note: If you want to store html into a blob, be sure to base64 encode it or it could break the serialize function.

Example encoding:

$YourSerializedData = base64_encode(serialize($theHTML));

$YourSerializedData is now ready to be stored in blob.

After getting data from blob you need to base64_decode then unserialize Example decoding:

$theHTML = unserialize(base64_decode($YourSerializedData));

Regex allow digits and a single dot

My try is combined solution.

string = string.replace(',', '.').replace(/[^\d\.]/g, "").replace(/\./, "x").replace(/\./g, "").replace(/x/, ".");
string = Math.round( parseFloat(string) * 100) / 100;

First line solution from here: regex replacing multiple periods in floating number . It replaces comma "," with dot "." ; Replaces first comma with x; Removes all dots and replaces x back to dot.

Second line cleans numbers after dot.

How to convert a data frame column to numeric type?

I would have added a comment (cant low rating)

Just to add on user276042 and pangratz

dat$x = as.numeric(as.character(dat$x))

This will override the values of existing column x

How to get a Docker container's IP address from the host

The --format option of inspect comes to the rescue.

Modern Docker client syntax is:

docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id

Old Docker client syntax is:

docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id

These commands will return the Docker container's IP address.

As mentioned in the comments: if you are on Windows, use double quotes " instead of single quotes ' around the curly braces.