Programs & Examples On #Filebuf

0

How to add new line in Markdown presentation?

Just add \ at the end of line. For example

one\
two

Will become

one
two

It's also better than two spaces because it's visible.

What is the difference between WCF and WPF?

  • WPF is your FrontEnd (presentation: .htm, .xaml & .css, ..)
  • WCF is your BackEnd app (services that involve server connections to acquire data for you to deliver to the FrontEnd to present). You can write WCF for RESTful model.
  • WebAPI is for building services of RESTful model for 4.+ frameworks.

How to go to a URL using jQuery?

//As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");

//like if you click on a link (it will be saved in the session history, 
//so the back button will work as expected)
window.location.href = "http://www.google.com";

Set UILabel line spacing

You can control line spacing in the storyboard:

duplicate question

How to properly compare two Integers in Java?

Because comparaison method have to be done based on type int (x==y) or class Integer (x.equals(y)) with right operator

public class Example {

    public static void main(String[] args) {
     int[] arr = {-32735, -32735, -32700, -32645, -32645, -32560, -32560};

        for(int j=1; j<arr.length-1; j++)
            if((arr[j-1]!=arr[j]) && (arr[j]!=arr[j+1])) 
                System.out.println("int>"+arr[j]);


    Integer[] I_arr = {-32735, -32735, -32700, -32645, -32645, -32560, -32560};

        for(int j=1; j<I_arr.length-1; j++)
            if((!I_arr[j-1].equals(I_arr[j])) && (!I_arr[j].equals(I_arr[j+1]))) 
                System.out.println("Interger>"+I_arr[j]);
    }
}

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I'm not sure how efficient this is but you can use range() to slice in both axis

 x=np.arange(16).reshape((4,4))
 x[range(1,3), :][:,range(1,3)] 

c++ parse int from string

You can use boost::lexical_cast:

#include <iostream>
#include <boost/lexical_cast.hpp>

int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;

   try   {
      i = boost::lexical_cast<int>( s1 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   try   {
      i = boost::lexical_cast<int>( s2 );
   }
   catch( boost::bad_lexical_cast & e ){
      std::cout << "Exception caught : " << e.what() << std::endl;
   }

   return 0;
}

How to find an available port?

If you need in range use:

public int nextFreePort(int from, int to) {
    int port = randPort(from, to);
    while (true) {
        if (isLocalPortFree(port)) {
            return port;
        } else {
            port = ThreadLocalRandom.current().nextInt(from, to);
        }
    }
}

private boolean isLocalPortFree(int port) {
    try {
        new ServerSocket(port).close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

AngularJS ng-if with multiple conditions

OR operator:

<div ng-repeat="k in items">
    <div ng-if="k || 'a' or k == 'b'">
        <!-- SOME CONTENT -->
    </div>
</div>

Even though it is simple enough to read, I hope as a developer you are use better names than 'a' 'k' 'b' etc..

For Example:

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin || group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

Another OR example

<p ng-if="group.title != 'Dispatcher News' or group.title != 'Coordinator News'" style="padding: 5px;">No links in group.</p>

AND operator (For those stumbling across this stackoverflow answer looking for an AND instead of OR condition)

<div class="links-group" ng-repeat="group in groups" ng-show="!group.hidden">
    <li ng-if="user.groups.admin && group.title == 'Home Pages'"> 
        <!--Content-->
    </li>
</div>

Sorting A ListView By Column

I sort using column name to set any sorting specifics that may need to be handled based on data type stored in the column and or if the column has already been sorted on(asc/desc). Here's a snippet from my ColumnClick event handler.

private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ListViewItemComparer sorter = GetListViewSorter(e.Column);

        listView.ListViewItemSorter = sorter;
        listView.Sort();
    }

    private ListViewItemComparer GetListViewSorter(int columnIndex)
    {
        ListViewItemComparer sorter = (ListViewItemComparer)listView.ListViewItemSorter;
        if (sorter == null)
        {
            sorter = new ListViewItemComparer();
        }

        sorter.ColumnIndex = columnIndex;

        string columnName = packagedEstimateListView.Columns[columnIndex].Name;
        switch (columnName)
        {
            case ApplicationModel.DisplayColumns.DateCreated:
            case ApplicationModel.DisplayColumns.DateUpdated:
                sorter.ColumnType = ColumnDataType.DateTime;
                break;
            case ApplicationModel.DisplayColumns.NetTotal:
            case ApplicationModel.DisplayColumns.GrossTotal:
                sorter.ColumnType = ColumnDataType.Decimal;
                break;
            default:
                sorter.ColumnType = ColumnDataType.String;
                break;
        }

        if (sorter.SortDirection == SortOrder.Ascending)
        {
            sorter.SortDirection = SortOrder.Descending;
        }
        else
        {
            sorter.SortDirection = SortOrder.Ascending;
        }

        return sorter;
    }

Below is my ListViewItemComparer

public class ListViewItemComparer : IComparer
{
    private int _columnIndex;
    public int ColumnIndex
    {
        get
        {
            return _columnIndex;
        }
        set
        {
            _columnIndex = value;
        }
    }

    private SortOrder _sortDirection;
    public SortOrder SortDirection
    {
        get
        {
            return _sortDirection;
        }
        set
        {
            _sortDirection = value;
        }
    }

    private ColumnDataType _columnType;
    public ColumnDataType ColumnType
    {
        get
        {
            return _columnType;
        }
        set
        {
            _columnType = value;
        }
    }


    public ListViewItemComparer()
    {
        _sortDirection = SortOrder.None;
    }

    public int Compare(object x, object y)
    {
        ListViewItem lviX = x as ListViewItem;
        ListViewItem lviY = y as ListViewItem;

        int result;

        if (lviX == null && lviY == null)
        {
            result = 0;
        }
        else if (lviX == null)
        {
            result = -1;
        }

        else if (lviY == null)
        {
            result = 1;
        }

        switch (ColumnType)
        {
            case ColumnDataType.DateTime:
                DateTime xDt = DataParseUtility.ParseDate(lviX.SubItems[ColumnIndex].Text);
                DateTime yDt = DataParseUtility.ParseDate(lviY.SubItems[ColumnIndex].Text);
                result = DateTime.Compare(xDt, yDt);
                break;

            case ColumnDataType.Decimal:
                Decimal xD = DataParseUtility.ParseDecimal(lviX.SubItems[ColumnIndex].Text.Replace("$", string.Empty).Replace(",", string.Empty));
                Decimal yD = DataParseUtility.ParseDecimal(lviY.SubItems[ColumnIndex].Text.Replace("$", string.Empty).Replace(",", string.Empty));
                result = Decimal.Compare(xD, yD);
                break;
            case ColumnDataType.Short:
                short xShort = DataParseUtility.ParseShort(lviX.SubItems[ColumnIndex].Text);
                short yShort = DataParseUtility.ParseShort(lviY.SubItems[ColumnIndex].Text);
                result = xShort.CompareTo(yShort);
                break;
            case ColumnDataType.Int:
                int xInt = DataParseUtility.ParseInt(lviX.SubItems[ColumnIndex].Text);
                int yInt = DataParseUtility.ParseInt(lviY.SubItems[ColumnIndex].Text);
                return xInt.CompareTo(yInt);
                break;
            case ColumnDataType.Long:
                long xLong = DataParseUtility.ParseLong(lviX.SubItems[ColumnIndex].Text);
                long yLong = DataParseUtility.ParseLong(lviY.SubItems[ColumnIndex].Text);
                return xLong.CompareTo(yLong);
                break;
            default:

                result = string.Compare(
                    lviX.SubItems[ColumnIndex].Text,
                    lviY.SubItems[ColumnIndex].Text,
                    false);

                break;
        }

        if (SortDirection == SortOrder.Descending)
        {
            return -result;
        }
        else
        {
            return result;
        }
    }
}

How do I make WRAP_CONTENT work on a RecyclerView

RecyclerView added support for wrap_content in 23.2.0 which was buggy , 23.2.1 was just stable , so you can use:

compile 'com.android.support:recyclerview-v7:24.2.0'

You can see the revision history here:

https://developer.android.com/topic/libraries/support-library/revisions.html

Note:

Also note that after updating support library the RecyclerView will respect wrap_content as well as match_parent so if you have a Item View of a RecyclerView set as match_parent the single view will fill whole screen

Multiple Cursors in Sublime Text 2 Windows

In Sublime Text, after you select multiple regions of text, a click is considered a way to exit the multi-select mode. Move the cursor with the keyboard keys (arrows, Ctrl+arrows, etc.) instead, and you'll be fine

How to pass a parameter like title, summary and image in a Facebook sharer URL

I've used the below before, and it has worked. It isn't very pretty, but you can alter it to suit your needs.

The following JavaScript function grabs the location.href & document.title for the sharer, and you can ultimately change these.

function fbs_click() {
        u=location.href;
        t=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),
                'sharer',
                'toolbar=0,status=0,width=626,height=436');

            return false;
        }

Usage:

<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank">
    Share on Facebook
</a>

It looks like this is what you could possibly be looking for: Facebook sharer title / desc....

Check if instance is of a type

As others have mentioned, the "is" keyword. However, if you're going to later cast it to that type, eg.

TForm t = (TForm)c;

Then you should use the "as" keyword.

e.g. TForm t = c as TForm.

Then you can check

if(t != null)
{
 // put TForm specific stuff here
}

Don't combine as with is because it's a duplicate check.

jquery, find next element by class

In this case you need to go up to the <tr> then use .next(), like this:

$(obj).closest('tr').next().find('.class');

Or if there may be rows in-between without the .class inside, you can use .nextAll(), like this:

$(obj).closest('tr').nextAll(':has(.class):first').find('.class');

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

Delete package.json and package-lock.json file

Then type npm init

after that type npm install socket.io --save

finally type npm install

It works for me

How to convert Nvarchar column to INT

I know its Too late But I hope it will work new comers Try This Its Working ... :D

select 
  case 
      when isnumeric(my_NvarcharColumn) = 1 then 
              cast(my_NvarcharColumn AS int)
      else
              NULL
 end

AS 'my_NvarcharColumnmitter'
from A

What is the difference between a mutable and immutable string in C#?

Here is the example for Immutable string and Mutable string builder

        Console.WriteLine("Mutable String Builder");
        Console.WriteLine("....................................");
        Console.WriteLine();
        StringBuilder sb = new StringBuilder("Very Good Morning");
        Console.WriteLine(sb.ToString());
        sb.Remove(0, 5);
        Console.WriteLine(sb.ToString());

        Console.WriteLine();

        Console.WriteLine("Immutable String");
        Console.WriteLine("....................................");
        Console.WriteLine();
        string s = "Very Good Morning";
        Console.WriteLine(s);
        s.Substring(0, 5);
        Console.WriteLine(s);
        Console.ReadLine();

angularjs ng-style: background-image isn't working

For those who are struggling to get this working with IE11

HTML

<div ng-style="getBackgroundStyle(imagepath)"></div>

JS

$scope.getBackgroundStyle = function(imagepath){
    return {
        'background-image':'url(' + imagepath + ')'
    }
}

Error handling in getJSON calls

Someone give Luciano these points :) I just tested his answer -had a similar question- and worked perfectly...

I even add my 50 cents:

.error(function(jqXHR, textStatus, errorThrown) {
        console.log("error " + textStatus);
        console.log("incoming Text " + jqXHR.responseText);
    })

JQuery Find #ID, RemoveClass and AddClass

.....

$("#testID #testID2").removeClass("test2").addClass("test3");

Because you have assigned an id to img too, you can simply do this too:

$("#testID2").removeClass("test2").addClass("test3");

And finally, you can do this too:

$("#testID img").removeClass("test2").addClass("test3");

Python - Move and overwrite files and folders

Use copy() instead, which is willing to overwrite destination files. If you then want the first tree to go away, just rmtree() it separately once you are done iterating over it.

http://docs.python.org/library/shutil.html#shutil.copy

http://docs.python.org/library/shutil.html#shutil.rmtree

Update:

Do an os.walk() over the source tree. For each directory, check if it exists on the destination side, and os.makedirs() it if it is missing. For each file, simply shutil.copy() and the file will be created or overwritten, whichever is appropriate.

How to add an image in the title bar using html?

Showing image in title bar is easy. please follow the steps :

a) first save you image some where in the folder and name like favicon. b) then use below line inside head tag of the html view

<link rel="icon" type="image/png" href="image_url" />

c) Here you must know the path of your file, where you have saved the image d) save your image url in place of image_url e) save your working.

How do I Convert DateTime.now to UTC in Ruby?

d = DateTime.now.utc

Oops!

That seems to work in Rails, but not vanilla Ruby (and of course that is what the question is asking)

d = Time.now.utc

Does work however.

Is there any reason you need to use DateTime and not Time? Time should include everything you need:

irb(main):016:0> Time.now
=> Thu Apr 16 12:40:44 +0100 2009

How to get a list of current open windows/process with Java?

This might be useful for apps with a bundled JRE: I scan for the folder name that i'm running the application from: so if you're application is executing from:

C:\Dev\build\SomeJavaApp\jre-9.0.1\bin\javaw.exe

then you can find if it's already running in J9, by:

public static void main(String[] args) {
    AtomicBoolean isRunning = new AtomicBoolean(false);
    ProcessHandle.allProcesses()
            .filter(ph -> ph.info().command().isPresent() && ph.info().command().get().contains("SomeJavaApp"))
            .forEach((process) -> {
                isRunning.set(true);
            });
    if (isRunning.get()) System.out.println("SomeJavaApp is running already");
}

Is it possible to make Font Awesome icons larger than 'fa-5x'?

You can redefine/overwrite the default font-awesome sizes and also add you own sizes

.fa-1x{
    font-size:0.8em;
}
.fa-2x{
    font-size:1em;
}
.fa-3x{
    font-size:1.2em;
}
.fa-4x{
    font-size:1.4em;
}
.fa-5x{
    font-size:1.6em;
}
.fa-mycustomx{
    font-size:3.2em;
}

Add a dependency in Maven

Actually, on investigating this, I think all these answers are incorrect. Your question is misleading because of our level of understanding of maven. And I say our because I'm just getting introduced to maven.

In Eclipse, when you want to add a jar file to your project, normally you download the jar manually and then drop it into the lib directory. With maven, you don't do it this way. Here's what you do:

  • Go to mvnrepository
  • Search for the library you want to add
  • Copy the dependency statement into your pom.xml
  • rebuild via mvn

Now, maven will connect and download the jar along with the list of dependencies, and automatically resolve any additional dependencies that jar may have had. So if the jar also needed commons-logging, that will be downloaded as well.

Git keeps asking me for my ssh key passphrase

Try adding this to your ~/.ssh/config:

Host *
   AddKeysToAgent yes
   UseKeychain yes
   IdentityFile ~/.ssh/id_rsa

... assuming your private key is named id_rsa

unix sort descending order

If you only want to sort only on the 5th field then use -k5,5.

Also, use the -t command line switch to specify the delimiter to tab. Try this:

sort  -k5,5 -r -n -t \t filename

or if the above doesn't work (with the tab) this:

sort  -k5,5 -r -n -t $'\t' filename

The man page for sort states:

-t, --field-separator=SEP use SEP instead of non-blank to blank transition

Finally, this SO question Unix Sort with Tab Delimiter might be helpful.

Login failed for user 'DOMAIN\MACHINENAME$'

Appreciate there are a few good answers here, but as I've just lost time working this out, hopefully this can help someone.

In my case, everything had been working fine, then stopped for no apparent reason with the error stated in the question.

IIS was running as Network service and Network Service had been set up on SQL Server previously (see other answers to this post). Server roles and user mappings looked correct.

The issue was; for absolutely no apparent reason; Network Service had switched to 'Deny' Login rights in the database.

To fix:

  1. Open SSMS > Security > Logins.
  2. Right click 'NT AUTHORITY\NETWORK SERVICE' and Click Properties.
  3. Go to 'Status' tab and set Permission to Connect To Database Engine To 'Grant'.

Network Service Allowed

Python math module

In

from math import sqrt

Using sqrt(4) works perfectly well. You need to only use math.sqrt(4) when you just use "import math".

Maven: How to include jars, which are not available in reps into a J2EE project?

For people wanting a quick solution to this problem:

<dependency>
  <groupId>LIB_NAME</groupId>
  <artifactId>LIB_NAME</artifactId>
  <version>1.0.0</version>
  <scope>system</scope>
  <systemPath>${basedir}/WebContent/WEB-INF/lib/YOUR_LIB.jar</systemPath>
</dependency>

just give your library a unique groupID and artifact name and point to where it is in the file system. You are good to go.

Of course this is a dirty quick fix that will ONLY work on your machine and if you don't change the path to the libs. But some times, that's all you want, to run and do a few tests.

EDIT: just re-red the question and realised the user was already using my solution as a temporary fix. I'll leave my answer as a quick help for others that come to this question. If anyone disagrees with this please leave me a comment. :)

Android Layout Weight

It doesn't work because you are using fill_parent as the width. The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.

How do I write a custom init for a UIView subclass in Swift?

Here is how I do a Subview on iOS in Swift -

class CustomSubview : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        let windowHeight : CGFloat = 150;
        let windowWidth  : CGFloat = 360;

        self.backgroundColor = UIColor.whiteColor();
        self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
        self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);

        //for debug validation
        self.backgroundColor = UIColor.grayColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Can we pass parameters to a view in SQL?

No you can't, as Mladen Prajdic said. Think of a view as a "static filter" on a table or a combination of tables. For example: a view may combine tables Order and Customer so you get a new "table" of rows from Order along with new columns containing the customer's name and the customer number (combination of tables). Or you might create a view that selects only unprocessed orders from the Order table (static filter).

You'd then select from the view like you would select from any other "normal" table - all "non-static" filtering must be done outside the view (like "Get all the orders for customers called Miller" or "Get unprocessed orders that came in on Dec 24th").

Declare variable in SQLite and use it

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.

I've used the below approach for large projects and works like a charm.

/* Create in-memory temp table for variables */
BEGIN;

PRAGMA temp_store = 2;
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);

/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');

/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';

/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...

DROP TABLE _Variables;
END;

Postgresql SELECT if string contains

I personally prefer the simpler syntax of the ~ operator.

SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' ~ tag_name;

Worth reading through Difference between LIKE and ~ in Postgres to understand the difference. `

What is the result of % in Python?

I have found that the easiest way to grasp the modulus operator (%) is through long division. It is the remainder and can be useful in determining a number to be even or odd:

4%2 = 0

  2
2|4
 -4
  0


11%3 = 2

  3
3|11
 -9
  2

How to pass variable from jade template file to a script file?

Here's how I addressed this (using a MEAN derivative)

My variables:

{
  NODE_ENV : development,
  ...
  ui_varables {
     var1: one,
     var2: two
  }
}

First I had to make sure that the necessary config variables were being passed. MEAN uses the node nconf package, and by default is set up to limit which variables get passed from the environment. I had to remedy that:

config/config.js:

original:

nconf.argv()
  .env(['PORT', 'NODE_ENV', 'FORCE_DB_SYNC'] ) // Load only these environment variables
  .defaults({
  store: {
    NODE_ENV: 'development'
  }
});

after modifications:

nconf.argv()
  .env('__') // Load ALL environment variables
  // double-underscore replaces : as a way to denote hierarchy
  .defaults({
  store: {
    NODE_ENV: 'development'
  }
});

Now I can set my variables like this:

export ui_varables__var1=first-value
export ui_varables__var2=second-value

Note: I reset the "heirarchy indicator" to "__" (double underscore) because its default was ":", which makes variables more difficult to set from bash. See another post on this thread.

Now the jade part: Next the values need to be rendered, so that javascript can pick them up on the client side. A straightforward way to write these values to the index file. Because this is a one-page app (angular), this page is always loaded first. I think ideally this should be a javascript include file (just to keep things clean), but this is good for a demo.

app/controllers/index.js:

'use strict';
var config = require('../../config/config');

exports.render = function(req, res) {
  res.render('index', {
    user: req.user ? JSON.stringify(req.user) : "null",
    //new lines follow:
    config_defaults : {
       ui_defaults: JSON.stringify(config.configwriter_ui).replace(/<\//g, '<\\/')  //NOTE: the replace is xss prevention
    }
  });
};

app/views/index.jade:

extends layouts/default

block content
  section(ui-view)
    script(type="text/javascript").
    window.user = !{user};
    //new line here
    defaults = !{config_defaults.ui_defaults};

In my rendered html, this gives me a nice little script:

<script type="text/javascript">
 window.user = null;         
 defaults = {"var1":"first-value","var2:"second-value"};
</script>        

From this point it's easy for angular to utilize the code.

Array Length in Java

In Java, your "actual" and "logical" size are the same. The run-time fills all array slots with default values upon allocation. So, your a contains 10.

How to scanf only integer?

Try using the following pattern in scanf. It will read until the end of the line:

scanf("%d\n", &n)

You won't need the getchar() inside the loop since scanf will read the whole line. The floats won't match the scanf pattern and the prompt will ask for an integer again.

How to pass command-line arguments to a PowerShell ps1 file

After digging through the PowerShell documentation, I discovered some useful information about this issue. You can't use the $args if you used the param(...) at the beginning of your file; instead you will need to use $PSBoundParameters. I copy/pasted your code into a PowerShell script, and it worked as you'd expect in PowerShell version 2 (I am not sure what version you were on when you ran into this issue).

If you are using $PSBoundParameters (and this ONLY works if you are using param(...) at the beginning of your script), then it is not an array, it is a hash table, so you will need to reference it using the key / value pair.

param($p1, $p2, $p3, $p4)
$Script:args=""
write-host "Num Args: " $PSBoundParameters.Keys.Count
foreach ($key in $PSBoundParameters.keys) {
    $Script:args+= "`$$key=" + $PSBoundParameters["$key"] + "  "
}
write-host $Script:args

And when called with...

PS> ./foo.ps1 a b c d

The result is...

Num Args:  4
$p1=a  $p2=b  $p3=c  $p4=d

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

I had the similar issue. I solved it the following way after a number of attempts to follow the pieces of advice in the forums. I am reposting the solution because it could be helpful for others.

I am running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file "httpd.conf" (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if "php.ini" is read from the right directory. Just type in your browser "localhost/index.php". The code of index.php is the following:

<?php echo phpinfo(); ?>

There is the row (not far from the top) called "Loaded Configuration File". So, if there is nothing added, then the problem could be that your "php.ini" is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from

PHPIniDir 'c:\PHP\'

to

PHPIniDir 'c:\PHP'

Pay the attention that the last slash disturbed everything!

Now the row "Loaded Configuration File" gets "C:\PHP\php.ini" after refreshing "localhost/index.php" (before I restarted Apache2.2) as well as mysql block is there. MySQL and PHP are working together!

Execute a SQL Stored Procedure and process the results

My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code

Please make sure that your procedure return some rows

Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
    Try
        Connection.Connect()
        debug.print("Look up account number " & AccountNumber)
        Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
        Dim DST As New DataSet
        DP.Fill(DST)
        Return DST.Tables(0)      
    Catch ex As Exception
        Return Nothing
    End Try
End Function

Concatenate two NumPy arrays vertically

Because both a and b have only one axis, as their shape is (3), and the axis parameter specifically refers to the axis of the elements to concatenate.

this example should clarify what concatenate is doing with axis. Take two vectors with two axis, with shape (2,3):

a = np.array([[1,5,9], [2,6,10]])
b = np.array([[3,7,11], [4,8,12]])

concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):

np.concatenate((a,b), axis=0)
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):

np.concatenate((a, b), axis=1)
array([[ 1,  5,  9,  3,  7, 11],
       [ 2,  6, 10,  4,  8, 12]])

to obtain the output you presented, you can use vstack

a = np.array([1,2,3])
b = np.array([4,5,6])
np.vstack((a, b))
array([[1, 2, 3],
       [4, 5, 6]])

You can still do it with concatenate, but you need to reshape them first:

np.concatenate((a.reshape(1,3), b.reshape(1,3)))
array([[1, 2, 3],
       [4, 5, 6]])

Finally, as proposed in the comments, one way to reshape them is to use newaxis:

np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))

Explicitly select items from a list or tuple

>>> map(myList.__getitem__, (2,2,1,3))
('baz', 'baz', 'bar', 'quux')

You can also create your own List class which supports tuples as arguments to __getitem__ if you want to be able to do myList[(2,2,1,3)].

What is JavaScript garbage collection?

Reference types do not store the object directly into the variable to which it is assigned, so the object variable in the example below, doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory, where the object exists.

var object = new Object();

if you assign one reference typed variable to another, each variable gets a copy of the pointer, and both still reference to the same object in memory.

var object1 = new Object();
var object2 = object1;

Two variables pointing to one object

JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.

var object1 = new Object();
// do something
object1 = null; // dereference

Dereferencing objects is especially important in very large applications that use millions of objects.

from The Principles of Object-Oriented JavaScript - NICHOLAS C. ZAKAS

System.Security.SecurityException when writing to Event Log

I ran into the same issue, but I had to go up one level and give full access to everyone to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\ key, instead of going down to security, that cleared up the issue for me.

How do I get the first element from an IEnumerable<T> in .net?

If your IEnumerable doesn't expose it's <T> and Linq fails, you can write a method using reflection:

public static T GetEnumeratedItem<T>(Object items, int index) where T : class
{
  T item = null;
  if (items != null)
  {
    System.Reflection.MethodInfo mi = items.GetType()
      .GetMethod("GetEnumerator");
    if (mi != null)
    {
      object o = mi.Invoke(items, null);
      if (o != null)
      {
        System.Reflection.MethodInfo mn = o.GetType()
          .GetMethod("MoveNext");
        if (mn != null)
        {
          object next = mn.Invoke(o, null);
          while (next != null && next.ToString() == "True")
          {
            if (index < 1)
            {
              System.Reflection.PropertyInfo pi = o
                .GetType().GetProperty("Current");
              if (pi != null) item = pi
                .GetValue(o, null) as T;
              break;
            }
            index--;
          }
        }
      }
    }
  }
  return item;
}

Best way to remove duplicate entries from a data table

You can use the DefaultView.ToTable method of a DataTable to do the filtering like this (adapt to C#):

 Public Sub RemoveDuplicateRows(ByRef rDataTable As DataTable)
    Dim pNewDataTable As DataTable
    Dim pCurrentRowCopy As DataRow
    Dim pColumnList As New List(Of String)
    Dim pColumn As DataColumn

    'Build column list
    For Each pColumn In rDataTable.Columns
        pColumnList.Add(pColumn.ColumnName)
    Next

    'Filter by all columns
    pNewDataTable = rDataTable.DefaultView.ToTable(True, pColumnList.ToArray)

    rDataTable = rDataTable.Clone

    'Import rows into original table structure
    For Each pCurrentRowCopy In pNewDataTable.Rows
        rDataTable.ImportRow(pCurrentRowCopy)
    Next
End Sub

Git, How to reset origin/master to a commit?

origin/xxx branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).

What you need to do to update the remote is to force push your local changes to master:

git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master

Show/hide 'div' using JavaScript

You can Hide/Show Div using Js function. sample below

<script>
    function showDivAttid(){

        if(Your Condition) {

            document.getElementById("attid").style.display = 'inline';
        }
        else
        {
            document.getElementById("attid").style.display = 'none';
        }
    }

</script>

HTML -

<div  id="attid" style="display:none;">Show/Hide this text</div>

How can I add the new "Floating Action Button" between two widgets/layouts

Keep it Simple Adding Floating Action Button using TextView by giving rounded xml background. - Add compile com.android.support:design:23.1.1 to gradle file

  • Use CoordinatorLayout as root view.
  • Before Ending the CoordinatorLayout introduce a textView.
  • Inside Drawable draw a circle.

Circle Xml is

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid
        android:color="@color/colorPrimary"/>
    <size
        android:width="30dp"
        android:height="30dp"/>
</shape>

Layout xml is

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="5"
    >

    <RelativeLayout
        android:id="@+id/viewA"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1.6"
        android:background="@drawable/contact_bg"
        android:gravity="center_horizontal|center_vertical"
        >
        </RelativeLayout>

    <LinearLayout
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="3.4"
        android:orientation="vertical"
        android:padding="16dp"
        android:weightSum="10"
        >

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            >
            </LinearLayout>

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Name"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:id="@+id/name"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="Ritesh Kumar Singh"
                android:singleLine="true"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            </LinearLayout>



        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Phone"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:id="@+id/number"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="8283001122"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:singleLine="true"
                android:padding="3dp"
                />

        </LinearLayout>



        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Email"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="[email protected]"
                android:textSize="22dp"
                android:singleLine="true"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

        </LinearLayout>


        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="City"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="Panchkula"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:singleLine="true"
                android:padding="3dp"
                />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>


    <TextView
        android:id="@+id/floating"
        android:transitionName="@string/transition_name_circle"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="16dp"
        android:clickable="false"
        android:background="@drawable/circle"
        android:elevation="10dp"
        android:text="R"
        android:textSize="40dp"
        android:gravity="center"
        android:textColor="@android:color/black"
        app:layout_anchor="@id/viewA"
        app:layout_anchorGravity="bottom"/>

        </android.support.design.widget.CoordinatorLayout>

Click here to se how it Will look like

Number of days between past date and current date in Google spreadsheet

DAYS360 does not calculate what you want, i.e. the number of days passed between the two dates. Use simple subtraction (-) or MINUS(). I made an updated copy of @DrCord’s sample spreadsheet to illustrate this.

Are you SURE you want DAYS360? That is a specialized function used in the financial sector to simplify calculations for bonds. It assumes a 360 day year, with 12 months of 30 days each. If you really want actual days, you'll lose 6 days each year. [source]

how get yesterday and tomorrow datetime in c#

DateTime tomorrow = DateTime.Today.AddDays(1);
DateTime yesterday = DateTime.Today.AddDays(-1);

Get a list of all threads currently running in Java

Code snippet to get list of threads started by main thread:

import java.util.Set;

public class ThreadSet {
    public static void main(String args[]) throws Exception{
        Thread.currentThread().setName("ThreadSet");
        for ( int i=0; i< 3; i++){
            Thread t = new Thread(new MyThread());
            t.setName("MyThread:"+i);
            t.start();
        }
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        for ( Thread t : threadSet){
            if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){
                System.out.println("Thread :"+t+":"+"state:"+t.getState());
            }
        }
    }
}

class MyThread implements Runnable{
    public void run(){
        try{
            Thread.sleep(5000);
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

output:

Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[ThreadSet,5,main]:state:RUNNABLE

If you need all threads including system threads, which have not been started by your program, remove below condition.

if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup())

Now output:

Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[Reference Handler,10,system]:state:WAITING
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[ThreadSet,5,main]:state:RUNNABLE
Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[Finalizer,8,system]:state:WAITING
Thread :Thread[Signal Dispatcher,9,system]:state:RUNNABLE
Thread :Thread[Attach Listener,5,system]:state:RUNNABLE

HQL Hibernate INNER JOIN

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;

List<Address> addList=new ArrayList<Address>();


@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getEmpName() {
    return empName;
}
public void setEmpName(String empName) {
    this.empName = empName;
}

@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
    return addList;
}

public void setAddList(List<Address> addList) {
    this.addList = addList;
}
}

We have two entities Employee and Address with One to Many relationship.

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="address")
public class Address implements Serializable{

private static final long serialVersionUID = 1L;

private int address_id;
private String address;
Employee employee;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
    return address_id;
}
public void setAddress_id(int address_id) {
    this.address_id = address_id;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
    return employee;
}
public void setEmployee(Employee employee) {
    this.employee = employee;
}
}

By this way we can implement inner join between two tables

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class Main {

public static void main(String[] args) {
    saveEmployee();

    retrieveEmployee();

}

private static void saveEmployee() {
    Employee employee=new Employee();
    Employee employee1=new Employee();
    Employee employee2=new Employee();
    Employee employee3=new Employee();

    Address address=new Address();
    Address address1=new Address();
    Address address2=new Address();
    Address address3=new Address();

    address.setAddress("1485,Sector 42 b");
    address1.setAddress("1485,Sector 42 c");
    address2.setAddress("1485,Sector 42 d");
    address3.setAddress("1485,Sector 42 a");

    employee.setEmpName("Varun");
    employee1.setEmpName("Krishan");
    employee2.setEmpName("Aasif");
    employee3.setEmpName("Dut");

    address.setEmployee(employee);
    address1.setEmployee(employee1);
    address2.setEmployee(employee2);
    address3.setEmployee(employee3);

    employee.getAddList().add(address);
    employee1.getAddList().add(address1);
    employee2.getAddList().add(address2);
    employee3.getAddList().add(address3);

    Session session=HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();

    session.save(employee);
    session.save(employee1);
    session.save(employee2);
    session.save(employee3);
    session.getTransaction().commit();
    session.close();
}

private static void retrieveEmployee() {
    try{

    String sqlQuery="select e from Employee e inner join e.addList";

    Session session=HibernateUtil.getSessionFactory().openSession();

    Query query=session.createQuery(sqlQuery);

    List<Employee> list=query.list();

     list.stream().forEach((p)->{System.out.println(p.getEmpName());});     
    session.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.

 public class HibernateUtil {
 private static SessionFactory sessionFactory ;
 static {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(Employee.class);
    configuration.addAnnotatedClass(Address.class);
                  configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");                                
    configuration.setProperty("hibernate.connection.username", "root");     
    configuration.setProperty("hibernate.connection.password", "root");
    configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty(" hibernate.connection.pool_size", "10");


   // configuration
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
} 

How can I convert string to datetime with format specification in JavaScript?

You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.

Reference:

1. moment library: https://momentjs.com/

2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript

convertDate(date) {
        var momentDate = moment(date).format('hh : mm A');
        return momentDate;
}

and you can call this method like:

this.convertDate('2020-05-01T10:31:18.837Z');

I hope it helps. Enjoy coding.

ssh: connect to host github.com port 22: Connection timed out

Basic URL Rewriting

Git provides a way to rewrite URLs using git config. Simply issue the following command:

git config --global url."https://".insteadOf git://

Now, as if by magic, all git commands will perform a substitution of git:// to https://

source: git:// protocol blocked by company, how can I get around that?

get value from DataTable

It looks like you have accidentally declared DataType as an array rather than as a string.

Change line 3 to:

Dim DataType As String = myTableData.Rows(i).Item(1)

That should work.

In Java, can you modify a List while iterating through it?

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

Main differences between SOAP and RESTful web services in Java

SOAP

Simple Object Access Protocol (SOAP) is a standard, an XML language, defining a message architecture and message formats. It is used by Web services. It contains a description of the operations.

WSDL is an XML-based language for describing Web services and how to access them. It will run on SMTP, HTTP, FTP, etc. It requires middleware support and well-defined mechanism to define services like WSDL+XSD and WS-Policy. SOAP will return XML based data

REST

Representational State Transfer (RESTful) web services. They are second-generation Web services.

RESTful web services communicate via HTTP rather than SOAP-based services and do not require XML messages or WSDL service-API definitions. For REST middleware is not required, only HTTP support is needed. It is a WADL standard, REST can return XML, plain text, JSON, HTML, etc.

Looping through a DataTable

Please try the following code below:

//Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd).
//Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop.

using (reader = cmd.ExecuteReader())
{
// Load the Data table object
  dataTable.Load(reader);
  if (dataTable.Rows.Count > 0)
  {
    DataColumn col = dataTable.Columns["YourColumnName"];  
    foreach (DataRow row in dataTable.Rows)
    {                                   
       strJsonData = row[col].ToString();
    }
  }
}

Get public/external IP address?

The IPIFY API is nice, as it can respond in raw text and JSON. It can also do callbacks etc. The only problem is that it responds in IPv4, not 6.

How to create an empty matrix in R?

To get rid of the first column of NAs, you can do it with negative indexing (which removes indices from the R data set). For example:

output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6

# output = 
#           [,1] [,2] [,3]
#     [1,]    1    3    5
#     [2,]    2    4    6

output = output[,-1] # this removes column 1 for all rows

# output = 
#           [,1] [,2]
#     [1,]    3    5
#     [2,]    4    6

So you can just add output = output[,-1]after the for loop in your original code.

Java recursive Fibonacci sequence

A Fibbonacci sequence is one that sums the result of a number when added to the previous result starting with 1.

      so.. 1 + 1 = 2
           2 + 3 = 5
           3 + 5 = 8
           5 + 8 = 13
           8 + 13 = 21

Once we understand what Fibbonacci is, we can begin to break down the code.

public int fibonacci(int n)  {
    if(n == 0)
        return 0;
    else if(n == 1)
      return 1;
   else
      return fibonacci(n - 1) + fibonacci(n - 2);
}

The first if statment checks for a base case, where the loop can break out. The else if statement below that is doing the same, but it could be re-written like so...

    public int fibonacci(int n)  {
        if(n < 2)
             return n;

        return fibonacci(n - 1) + fibonacci(n - 2);
    }

Now that a base case is establish we have to understand the call stack.Your first call to "fibonacci" will be the last to resolve on the stack (sequence of calls) as they resolve in the reverse order from which they were called. The last method called resolves first, then the last to be called before that one and so on...

So, all the calls are made first before anything is "calculated" with those results. With an input of 8 we expect an output of 21 (see table above).

fibonacci(n - 1) keeps being called until it reaches the base case, then fibonacci(n - 2) is called until it reaches the base case. When the stack starts summing the result in reverse order, the result will be like so...

1 + 1 = 1        ---- last call of the stack (hits a base case).
2 + 1 = 3        ---- Next level of the stack (resolving backwards).
2 + 3 = 5        ---- Next level of the stack (continuing to resolve).

They keep bubbling (resolving backwards) up until the correct sum is returned to the first call in the stack and that's how you get your answer.

Having said that, this algorithm is very inefficient because it calculates the same result for each branch the code splits into. A much better approach is a "bottom up" one where no Memoization (caching) or recursion (deep call stack) is required.

Like so...

        static int BottomUpFib(int current)
        {
            if (current < 2) return current;

            int fib = 1;
            int last = 1;

            for (int i = 2; i < current; i++)
            {
                int temp = fib;
                fib += last;
                last = temp;
            }

            return fib;
        }

Volley - POST/GET parameters

To provide POST parameter send your parameter as JSONObject in to the JsonObjectRequest constructor. 3rd parameter accepts a JSONObject that is used in Request body.

JSONObject paramJson = new JSONObject();

paramJson.put("key1", "value1");
paramJson.put("key2", "value2");


JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,paramJson,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
requestQueue.add(jsonObjectRequest);

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Get the current date and time

use DateTime.Now

try this:

DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")

MySQL Install: ERROR: Failed to build gem native extension

If you use Percona Mysql server

$ yum install Percona-Server-devel-55

$ gem install mysql

Given a DateTime object, how do I get an ISO 8601 date in string format?

DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.

EDIT: To get the additional Z at the end as the OP requires, use "o" instead of "s".

Adding css class through aspx code behind

Assuming your div has some CSS classes already...

<div id="classMe" CssClass="first"></div>

The following won't replace existing definitions:

ClassMe.CssClass += " second";

And if you are not sure until the very last moment...

string classes = ClassMe.CssClass;
ClassMe.CssClass += (classes == "") ? "second" : " second";

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

You should probably stop using launch images in iOS 8 and use a storyboard or nib/xib.

  • In Xcode 6, open the File menu and choose New ? File... ? iOS ? User Interface ? Launch Screen.

  • Then open the settings for your project by clicking on it.

  • In the General tab, in the section called App Icons and Launch Images, set the Launch Screen File to the files you just created (this will set UILaunchStoryboardName in info.plist).

Note that for the time being the simulator will only show a black screen, so you need to test on a real device.

Adding a Launch Screen xib file to your project:

Adding a new Launch Screen xib file

Configuring your project to use the Launch Screen xib file instead of the Asset Catalog:

Configure project to use Launch Screen xob

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

A quick answer, that doesn't require you to edit any configuration files (and works on other operating systems as well as Windows), is to just find the directory that you are allowed to save to using:

mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-----------------------+
| Variable_name    | Value                 |
+------------------+-----------------------+
| secure_file_priv | /var/lib/mysql-files/ |
+------------------+-----------------------+
1 row in set (0.06 sec)

And then make sure you use that directory in your SELECT statement's INTO OUTFILE clause:

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Original answer

I've had the same problem since upgrading from MySQL 5.6.25 to 5.6.26.

In my case (on Windows), looking at the MySQL56 Windows service shows me that the options/settings file that is being used when the service starts is C:\ProgramData\MySQL\MySQL Server 5.6\my.ini

On linux the two most common locations are /etc/my.cnf or /etc/mysql/my.cnf.

MySQL56 Service

Opening this file I can see that the secure-file-priv option has been added under the [mysqld] group in this new version of MySQL Server with a default value:

secure-file-priv="C:/ProgramData/MySQL/MySQL Server 5.6/Uploads"

You could comment this (if you're in a non-production environment), or experiment with changing the setting (recently I had to set secure-file-priv = "" in order to disable the default). Don't forget to restart the service after making changes.

Alternatively, you could try saving your output into the permitted folder (the location may vary depending on your installation):

SELECT *
FROM xxxx
WHERE XXX
INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/report.csv'
    FIELDS TERMINATED BY '#'
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

It's more common to have comma seperate values using FIELDS TERMINATED BY ','. See below for an example (also showing a Linux path):

SELECT *
FROM table
INTO OUTFILE '/var/lib/mysql-files/report.csv'
    FIELDS TERMINATED BY ',' ENCLOSED BY '"'
    ESCAPED BY ''
    LINES TERMINATED BY '\n';

Hive cast string to date dd-MM-yyyy

Let's say you have a column 'birth_day' in your table which is in string format, you should use the following query to filter using birth_day

date_Format(birth_day, 'yyyy-MM-dd')

You can use it in a query in the following way

select * from yourtable
where 
date_Format(birth_day, 'yyyy-MM-dd') = '2019-04-16';

How to use PowerShell select-string to find more than one pattern in a file?

To search for multiple matches in each file, we can sequence several Select-String calls:

Get-ChildItem C:\Logs |
  where { $_ | Select-String -Pattern 'VendorEnquiry' } |
  where { $_ | Select-String -Pattern 'Failed' } |
  ...

At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.

Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:

filter MultiSelect-String( [string[]]$Patterns ) {
  # Check the current item against all patterns.
  foreach( $Pattern in $Patterns ) {
    # If one of the patterns does not match, skip the item.
    $matched = @($_ | Select-String -Pattern $Pattern)
    if( -not $matched ) {
      return
    }
  }

  # If all patterns matched, pass the item through.
  $_
}

Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...


Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:

function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
  $time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}

PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True

pythonic way to do something N times without an index variable?

A slightly faster approach than looping on xrange(N) is:

import itertools

for _ in itertools.repeat(None, N):
    do_something()

JavaScript - populate drop down list with array

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

Android: show/hide a view using an animation

I have used this two function to hide and show view with transition animation smoothly.

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void expand(final View v, int duration, int targetHeight, final int position) {

        int prevHeight = v.getHeight();

        v.setVisibility(View.VISIBLE);
        ValueAnimator valueAnimator = ValueAnimator.ofInt(0, targetHeight);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.getLayoutParams().height = (int) animation.getAnimatedValue();
                v.requestLayout();
            }
        });
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.setDuration(duration);
        valueAnimator.start();
        valueAnimator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                v.clearAnimation();
            }
        });

    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void collapse(final View v, int duration, int targetHeight, final int position) {
        if (position == (data.size() - 1)) {
            return;
        }
        int prevHeight = v.getHeight();
        ValueAnimator valueAnimator = ValueAnimator.ofInt(prevHeight, targetHeight);
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                v.getLayoutParams().height = (int) animation.getAnimatedValue();
                v.requestLayout();
            }
        });
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.setDuration(duration);
        valueAnimator.start();
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                animBoolArray.put(position, false);
                v.clearAnimation();

            }
        });
    }

Add Bootstrap Glyphicon to Input Box

Tested with Bootstrap 4.

Take a form-control, and add is-valid to its class. Notice how the control turns green, but more importantly, notice the checkmark icon on the right of the control? This is what we want!

Example:

_x000D_
_x000D_
.my-icon {_x000D_
    padding-right: calc(1.5em + .75rem);_x000D_
    background-image: url('https://use.fontawesome.com/releases/v5.8.2/svgs/regular/calendar-alt.svg');_x000D_
    background-repeat: no-repeat;_x000D_
    background-position: center right calc(.375em + .1875rem);_x000D_
    background-size: calc(.75em + .375rem) calc(.75em + .375rem);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
<div class="container">_x000D_
  <div class="col-md-5">_x000D_
 <input type="text" id="date" class="form-control my-icon" placeholder="Select...">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Apache won't follow symlinks (403 Forbidden)

The 403 error may also be caused by an encrypted file system, e.g. a symlink to an encrypted home folder.

If your symlink points into the encrypted folder, the apache user (e.g. www-data) cannot access the contents, even if apache and file/folder permissions are set correctly. Access of the www-data user can be tested with such a call:

sudo -u www-data ls -l /var/www/html/<your symlink>/

There are workarounds/solutions to this, e.g. adding the www-data user to your private group (exposes the encrypted data to the web user) or by setting up an unencrypted rsynced folder (probably rather secure). I for myself will probably go for an rsync solution during development.

https://askubuntu.com/questions/633625/public-folder-in-an-encrypted-home-directory

A convenient tool for my purposes is lsyncd. This allows me to work directly in my encrypted home folder and being able to see changes almost instantly in the apache web page. The synchronization is triggered by changes in the file system, calling an rsync. As I'm only working on rather small web pages and scripts, the syncing is very fast. I decided to use a short delay of 1 second before the rsync is started, even though it is possible to set a delay of 0 seconds.

Installing lsyncd (in Ubuntu):

sudo apt-get install lsyncd

Starting the background service:

lsyncd -delay 1 -rsync /home/<me>/<work folder>/ /var/www/html/<web folder>/

Class not registered Error

I had this problem and I solved it when I understood that it was looking for the Windows Registry specified in the brackets.

Since the error was happening only in one computer, what I had to do was export the registry from the computer that it was working and install it on the computer that was missing it.

MySQL order by before group by

No. It makes no sense to order the records before grouping, since grouping is going to mutate the result set. The subquery way is the preferred way. If this is going too slow you would have to change your table design, for example by storing the id of of the last post for each author in a seperate table, or introduce a boolean column indicating for each author which of his post is the last one.

How to set selected value from Combobox?

Use the SelectedIndex property for the respective employee status in the combo box.

Get current value selected in dropdown using jQuery

$("#citiesList").change(function() {
    alert($("#citiesList option:selected").text());
    alert($("#citiesList option:selected").val());              
});

citiesList is id of select tag

How to play YouTube video in my Android application?

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watchv=cxLG2wtE7TM"));
startActivity(intent);

Python requests - print entire http request (raw)?

Note: this answer is outdated. Newer versions of requests support getting the request content directly, as AntonioHerraizS's answer documents.

It's not possible to get the true raw content of the request out of requests, since it only deals with higher level objects, such as headers and method type. requests uses urllib3 to send requests, but urllib3 also doesn't deal with raw data - it uses httplib. Here's a representative stack trace of a request:

-> r= requests.get("http://google.com")
  /usr/local/lib/python2.7/dist-packages/requests/api.py(55)get()
-> return request('get', url, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/api.py(44)request()
-> return session.request(method=method, url=url, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/sessions.py(382)request()
-> resp = self.send(prep, **send_kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/sessions.py(485)send()
-> r = adapter.send(request, **kwargs)
  /usr/local/lib/python2.7/dist-packages/requests/adapters.py(324)send()
-> timeout=timeout
  /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(478)urlopen()
-> body=body, headers=headers)
  /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py(285)_make_request()
-> conn.request(method, url, **httplib_request_kw)
  /usr/lib/python2.7/httplib.py(958)request()
-> self._send_request(method, url, body, headers)

Inside the httplib machinery, we can see HTTPConnection._send_request indirectly uses HTTPConnection._send_output, which finally creates the raw request and body (if it exists), and uses HTTPConnection.send to send them separately. send finally reaches the socket.

Since there's no hooks for doing what you want, as a last resort you can monkey patch httplib to get the content. It's a fragile solution, and you may need to adapt it if httplib is changed. If you intend to distribute software using this solution, you may want to consider packaging httplib instead of using the system's, which is easy, since it's a pure python module.

Alas, without further ado, the solution:

import requests
import httplib

def patch_send():
    old_send= httplib.HTTPConnection.send
    def new_send( self, data ):
        print data
        return old_send(self, data) #return is not necessary, but never hurts, in case the library is changed
    httplib.HTTPConnection.send= new_send

patch_send()
requests.get("http://www.python.org")

which yields the output:

GET / HTTP/1.1
Host: www.python.org
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/2.1.0 CPython/2.7.3 Linux/3.2.0-23-generic-pae

Collections sort(List<T>,Comparator<? super T>) method example

This might be simplest way -

Collections.sort(listOfStudent,new Comparator<Student>(){
                     public int compare(Student s1,Student s2){
                           // Write your logic here.
                     }});

Using Java 8(lambda expression) -

listOfStudent.sort((s1, s2) -> s1.age - s2.age); 

Change the Right Margin of a View Programmatically?

EDIT: A more generic way of doing this that doesn't rely on the layout type (other than that it is a layout type which supports margins):

public static void setMargins (View v, int l, int t, int r, int b) {
    if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
        p.setMargins(l, t, r, b);
        v.requestLayout();
    }
}

You should check the docs for TextView. Basically, you'll want to get the TextView's LayoutParams object, and modify the margins, then set it back to the TextView. Assuming it's in a LinearLayout, try something like this:

TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);

I can't test it right now, so my casting may be off by a bit, but the LayoutParams are what need to be modified to change the margin.

NOTE

Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams

How do I resolve a TesseractNotFoundError?

The following three commands will do the needful :

sudo apt update
# This will update your packages
sudo apt install tesseract-ocr
# This will install OCR
sudo apt install libtesseract-dev
# This will add it as development dependency

Signing a Windows EXE file

You can try using Microsoft's Sign Tool

You download it as part of the Windows SDK for Windows Server 2008 and .NET 3.5. Once downloaded you can use it from the command line like so:

signtool sign /a MyFile.exe

This signs a single executable, using the "best certificate" available. (If you have no certificate, it will show a SignTool error message.)

Or you can try:

signtool signwizard

This will launch a wizard that will walk you through signing your application. (This option is not available after Windows SDK 7.0.)


If you'd like to get a hold of certificate that you can use to test your process of signing the executable you can use the .NET tool Makecert.

Certificate Creation Tool (Makecert.exe)

Once you've created your own certificate and have used it to sign your executable, you'll need to manually add it as a Trusted Root CA for your machine in order for UAC to tell the user running it that it's from a trusted source. Important. Installing a certificate as ROOT CA will endanger your users privacy. Look what happened with DELL. You can find more information for accomplishing this both in code and through Windows in:

Hopefully that provides some more information for anyone attempting to do this!

How can I view array structure in JavaScript with alert()?

For readability purposes you can use:

alert(JSON.stringify(someArrayOrObj, '', 2));

More about JSON.stringify().

Example:

let user = {
  name: "John",
  age: 30,
  roles: {
    isAdmin: false,
    isEditor: true
  }
};

alert(JSON.stringify(user, "", 2));
/* Result:
{
  "name": "John",
  "age": 30,
  "roles": {
    "isAdmin": false,
    "isEditor": true
  }
} 
*/

How to know function return type and argument types?

Yes, you should use docstrings to make your classes and functions more friendly to other programmers:

More: http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring

Some editors allow you to see docstrings while typing, so it really makes work easier.

How to prevent a click on a '#' link from jumping to top of page?

$('a[href="#"]').click(function(e) {e.preventDefault(); });

How to Apply global font to whole HTML document

Set it in the body selector of your css. E.g.

body {
    font: 16px Arial, sans-serif;
}

How do I use cascade delete with SQL Server?

You will need to,

  • Drop the existing foreign key constraint,
  • Add a new one with the ON DELETE CASCADE setting enabled.

Something like:

ALTER TABLE dbo.T2
   DROP CONSTRAINT FK_T1_T2   -- or whatever it's called

ALTER TABLE dbo.T2
   ADD CONSTRAINT FK_T1_T2_Cascade
   FOREIGN KEY (EmployeeID) REFERENCES dbo.T1(EmployeeID) ON DELETE CASCADE

Measuring elapsed time with the Time module

Vadim Shender response is great. You can also use a simpler decorator like below:

import datetime
def calc_timing(original_function):                            
    def new_function(*args,**kwargs):                        
        start = datetime.datetime.now()                     
        x = original_function(*args,**kwargs)                
        elapsed = datetime.datetime.now()                      
        print("Elapsed Time = {0}".format(elapsed-start))     
        return x                                             
    return new_function()  

@calc_timing
def a_func(*variables):
    print("do something big!")

How to run a single RSpec test?

Run the commands from your project's root directory:

# run all specs in the project's spec folder
bundle exec rspec 

# run specs nested under a directory, like controllers
bundle exec rspec spec/controllers

# run a single test file
bundle exec rspec spec/controllers/groups_controller_spec.rb

# run a test or subset of tests within a file
# e.g., if the 'it', 'describe', or 'context' block you wish to test
# starts at line 45, run:
bundle exec rspec spec/controllers/groups_controller_spec.rb:45

Lowercase and Uppercase with jQuery

If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform property:

.myclass {
    text-transform: lowercase;
}

See https://developer.mozilla.org/en/CSS/text-transform for more info.

However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

I had to move domain, username, password from

client.ClientCredentials.UserName.UserName = domain + "\\" + username; client.ClientCredentials.UserName.Password = password

to

client.ClientCredentials.Windows.ClientCredential.UserName = username; client.ClientCredentials.Windows.ClientCredential.Password = password; client.ClientCredentials.Windows.ClientCredential.Domain = domain;

Eclipse won't compile/run java file

  • Make a project to put the files in.
    • File -> New -> Java Project
    • Make note of where that project was created (where your "workspace" is)
  • Move your java files into the src folder which is immediately inside the project's folder.
    • Find the project INSIDE Eclipse's Package Explorer (Window -> Show View -> Package Explorer)
    • Double-click on the project, then double-click on the 'src' folder, and finally double-click on one of the java files inside the 'src' folder (they should look familiar!)
  • Now you can run the files as expected.

Note the hollow 'J' in the image. That indicates that the file is not part of a project.

Hollow J means it is not part of a project

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The PostgreSQL documentation on Character Types is a good reference for this. They are two different names for the same type.

How do I replace a character at a particular index in JavaScript?

I know this is old but the solution does not work for negative index so I add a patch to it. hope it helps someone

String.prototype.replaceAt=function(index, character) {
    if(index>-1) return this.substr(0, index) + character + this.substr(index+character.length);
    else return this.substr(0, this.length+index) + character + this.substr(index+character.length);

}

How to add external library in IntelliJ IDEA?

I've used this process to attach a 3rd party Jar to an Android project in IDEA.

  • Copy the Jar to your libs/ directory
  • Open Project Settings (Ctrl Alt Shift S)
  • Under the Project Settings panel on the left, choose Modules
  • On the larger right pane, choose the Dependencies tab
  • Press the Add... button on the far right of the screen (if you have a smaller screen like me, you may have to drag resize to the right in order to see it)
  • From the dropdown of Add options, choose "Library". A "Choose Libraries" dialog will appear.
  • Press "New Library..."
  • Choose a suitable title for the library
  • Press "Attach Classes..."
  • Choose the Jar from your libs/ directory, and press OK to dismiss

The library should now be recognised.

Could not load file or assembly '***.dll' or one of its dependencies

I had the same issue with a dll yesterday and all it referenced was System, System.Data, and System.Xml. Turns out the build configuration for the Platform type didn't line up. The dll was build for x86 and the program using it was "Any CPU" and since I am running a x64 machine, it ran the program as x64 and had issues with the x86 dll. I don't know if this is your issue or not, just thought that I would mention it as something else to check.

Convert text into number in MySQL query

Simply use CAST,

CAST(column_name AS UNSIGNED)

The type for the cast result can be one of the following values:

BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]

Activity restart on rotation Android

What you describe is the default behavior. You have to detect and handle these events yourself by adding:

android:configChanges

to your manifest and then the changes that you want to handle. So for orientation, you would use:

android:configChanges="orientation"

and for the keyboard being opened or closed you would use:

android:configChanges="keyboardHidden"

If you want to handle both you can just separate them with the pipe command like:

android:configChanges="keyboardHidden|orientation"

This will trigger the onConfigurationChanged method in whatever Activity you call. If you override the method you can pass in the new values.

Hope this helps.

How to find whether MySQL is installed in Red Hat?

Usually you can find a program under a subdirectory "../bin". System programs are under /usr/bin or /bin. To check where files of mysql package are placed, on RHEL 6 type like this :

rpm -ql mysql (which is the main part of the package)

and the result is a list of "exe" files such as "mysqladmin" tool. About to know the version of the server, run the command:

mysqladmin -u "valid-user" version

Distinct in Linq based on only one field of the table

You can try this:table1.GroupBy(t => t.Text).Select(shape => shape.r)).Distinct();

Pretty-Printing JSON with PHP

here's the function i use myself, the api is just like json_encode, except it has a 3rd argument exclude_flags in case you want to exclude some of the default flags (like JSON_UNESCAPED_SLASHES)

function json_encode_pretty($data, int $extra_flags = 0, int $exclude_flags = 0): string
{
    // prettiest flags for: 7.3.9
    $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | (defined("JSON_UNESCAPED_LINE_TERMINATORS") ? JSON_UNESCAPED_LINE_TERMINATORS : 0) | JSON_PRESERVE_ZERO_FRACTION | (defined("JSON_THROW_ON_ERROR") ? JSON_THROW_ON_ERROR : 0);
    $flags = ($flags | $extra_flags) & ~ $exclude_flags;
    return (json_encode($data, $flags));
}

Javascript array value is undefined ... how do I test for that

predQuery[preId]=='undefined'

You're testing against the string 'undefined'; you've confused this test with the typeof test which would return a string. You probably mean to be testing against the special value undefined:

predQuery[preId]===undefined

Note the strict-equality operator to avoid the generally-unwanted match null==undefined.

However there are two ways you can get an undefined value: either preId isn't a member of predQuery, or it is a member but has a value set to the special undefined value. Often, you only want to check whether it's present or not; in that case the in operator is more appropriate:

!(preId in predQuery)

How to read a file without newlines?

I think this is the best option.

temp = [line.strip() for line in file.readlines()]

'module' object is not callable - calling method in another file

The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

from other_file import findTheRange

if your file is named findTheRange too, following java's convenions, then you should write

from findTheRange import findTheRange

you can also import it just like you did with random:

import findTheRange
operator = findTheRange.findTheRange()

Some other comments:

a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

b) You can build the list directly:

  randomList = [random.randint(0, 100) for i in range(5)]

c) You can call methods in the same way you do in java:

largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)

d) You can use built in function, and the huge python library:

largestInList = max(randomList)
smallestInList = min(randomList)

e) If you still want to use a class, and you don't need self, you can use @staticmethod:

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...

Running a shell script through Cygwin on Windows

If you don't mind always including .sh on the script file name, then you can keep the same script for Cygwin and Unix (Macbook).

To illustrate:
1. Always include .sh to your script file name, e.g., test1.sh
2. test1.sh looks like the following as an example:
#!/bin/bash echo '$0 = ' $0 echo '$1 = ' $1 filepath=$1 3. On Windows with Cygwin, you type "test1.sh" to run
4. On a Unix, you also type "test1.sh" to run


Note: On Windows, you need to use the file explorer to do following once:
1. Open the file explorer
2. Right-click on a file with .sh extension, like test1.sh
3. Open with... -> Select sh.exe
After this, your Windows 10 remembers to execute all .sh files with sh.exe.

Note: Using this method, you do not need to prepend your script file name with bash to run

Custom Input[type="submit"] style not working with jquerymobile button

I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important property.

HTML

<a href="#" class="selected_btn" data-role="button">Button name</a>

CSS

.selected_btn
{
    border:1px solid red;
    text-decoration:none;
    font-family:helvetica;
    color:red !important;            
    background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}

Here is the demo

cursor.fetchall() vs list(cursor) in Python

If you are using the default cursor, a MySQLdb.cursors.Cursor, the entire result set will be stored on the client side (i.e. in a Python list) by the time the cursor.execute() is completed.

Therefore, even if you use

for row in cursor:

you will not be getting any reduction in memory footprint. The entire result set has already been stored in a list (See self._rows in MySQLdb/cursors.py).

However, if you use an SSCursor or SSDictCursor:

import MySQLdb
import MySQLdb.cursors as cursors

conn = MySQLdb.connect(..., cursorclass=cursors.SSCursor)

then the result set is stored in the server, mysqld. Now you can write

cursor = conn.cursor()
cursor.execute('SELECT * FROM HUGETABLE')
for row in cursor:
    print(row)

and the rows will be fetched one-by-one from the server, thus not requiring Python to build a huge list of tuples first, and thus saving on memory.

Otherwise, as others have already stated, cursor.fetchall() and list(cursor) are essentially the same.

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Try killing port 8600 with this command:

fuser -k 8600/tcp

That fixed it for me.

Alarm Manager Example

I have made my own implementation to do this on the simplest way as possible.

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import junit.framework.Assert;

/**
 * Created by Daniel on 28/08/2016.
 */
public abstract class AbstractSystemServiceTask {

    private final Context context;
    private final AlarmManager alarmManager;
    private final BroadcastReceiver broadcastReceiver;
    private final PendingIntent pendingIntent;

    public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType, final BackgroundTaskListener backgroundTaskListener) {

        Assert.assertNotNull("ApplicationContext can't be null", context);
        Assert.assertNotNull("ID can't be null", id);

        this.context = context;

        this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);

        this.context.registerReceiver(
                this.broadcastReceiver = this.getBroadcastReceiver(backgroundTaskListener),
                new IntentFilter(id));

        this.configAlarmManager(
                this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
                time,
                alarmType);
    }

    public void stop() {

        this.alarmManager.cancel(this.pendingIntent);
        this.context.unregisterReceiver(this.broadcastReceiver);
    }

    private BroadcastReceiver getBroadcastReceiver(final BackgroundTaskListener backgroundTaskListener) {

        Assert.assertNotNull("BackgroundTaskListener can't be null.", backgroundTaskListener);

        return new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                backgroundTaskListener.perform(context, intent);
            }
        };
    }

    private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {

        long ensurePositiveTime = Math.max(time, 0L);

        switch (alarmType) {
            case REPEAT:
                this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
                break;
            case ONE_TIME:
            default:
                this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
        }
    }

    public interface BackgroundTaskListener {

        void perform(Context context, Intent intent);

    }

    public enum AlarmType {

        REPEAT, ONE_TIME;

    }

}

The only next step, implement it.

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import ...AbstractSystemServiceTask;

import java.util.concurrent.TimeUnit;

/**
 * Created by Daniel on 28/08/2016.
 */
public class UpdateInfoSystemServiceTask extends AbstractSystemServiceTask {

    private final static String ID = "UPDATE_INFO_SYSTEM_SERVICE";
    private final static long REPEAT_TIME = TimeUnit.SECONDS.toMillis(10);
    private final static AlarmType ALARM_TYPE = AlarmType.REPEAT;

    public UpdateInfoSystemServiceTask(Context context) {

        super(context, ID, REPEAT_TIME, ALARM_TYPE, new BackgroundTaskListener() {

            @Override
            public void perform(Context context, Intent intent) {

                Log.i("MyAppLog", "-----> UpdateInfoSystemServiceTask");

                //DO HERE WHATEVER YOU WANT...
            }
        });

        Log.i("MyAppLog", "UpdateInfoSystemServiceTask started.");
    }

}

I like to work with this implementation, but another possible good way, it's don't make the AbstractSystemServiceTask class abstract, and build it through a Builder.

I hope it help you.

UPDATED Improved to allow several BackgroundTaskListener on the same BroadCastReceiver.

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import junit.framework.Assert;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Daniel on 28/08/2016.
 */
public abstract class AbstractSystemServiceTask {

    private final Context context;
    private final AlarmManager alarmManager;
    private final BroadcastReceiver broadcastReceiver;
    private final PendingIntent pendingIntent;

    private final Set<BackgroundTaskListener> backgroundTaskListenerSet;

    public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType) {

        Assert.assertNotNull("ApplicationContext can't be null", context);
        Assert.assertNotNull("ID can't be null", id);

        this.backgroundTaskListenerSet = new HashSet<>();

        this.context = context;

        this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);

        this.context.registerReceiver(
                this.broadcastReceiver = this.getBroadcastReceiver(),
                new IntentFilter(id));

        this.configAlarmManager(
                this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
                time,
                alarmType);
    }

    public synchronized void registerTask(final BackgroundTaskListener backgroundTaskListener) {

        Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);

        this.backgroundTaskListenerSet.add(backgroundTaskListener);
    }

    public synchronized void removeTask(final BackgroundTaskListener backgroundTaskListener) {

        Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);

        this.backgroundTaskListenerSet.remove(backgroundTaskListener);
    }

    public void stop() {

        this.backgroundTaskListenerSet.clear();

        this.alarmManager.cancel(this.pendingIntent);
        this.context.unregisterReceiver(this.broadcastReceiver);
    }

    private BroadcastReceiver getBroadcastReceiver() {

        return new BroadcastReceiver() {

            @Override
            public void onReceive(final Context context, final Intent intent) {

                for (BackgroundTaskListener backgroundTaskListener : AbstractSystemServiceTask.this.backgroundTaskListenerSet) {

                    backgroundTaskListener.perform(context, intent);
                }
            }
        };
    }

    private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {

        long ensurePositiveTime = Math.max(time, 0L);

        switch (alarmType) {
            case REPEAT:
                this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
                break;
            case ONE_TIME:
            default:
                this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
        }
    }

    public interface BackgroundTaskListener {

        void perform(Context context, Intent intent);

    }

    public enum AlarmType {

        REPEAT, ONE_TIME;

    }

}

Batch script to delete files

There's multiple ways of doing things in batch, so if escaping with a double percent %% isn't working for you, then you could try something like this:

set olddir=%CD%
cd /d "path of folder"
del "file name/ or *.txt etc..."
cd /d "%olddir%"

How this works:

set olddir=%CD% sets the variable "olddir" or any other variable name you like to the directory your batch file was launched from.

cd /d "path of folder" changes the current directory the batch will be looking at. keep the quotations and change path of folder to which ever path you aiming for.

del "file name/ or *.txt etc..." will delete the file in the current directory your batch is looking at, just don't add a directory path before the file name and just have the full file name or, to delete multiple files with the same extension with *.txt or whatever extension you need.

cd /d "%olddir%" takes the variable saved with your old path and goes back to the directory you started the batch with, its not important if you don't want the batch going back to its previous directory path, and like stated before the variable name can be changed to whatever you wish by changing the set olddir=%CD% line.

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:

sys.path.insert(1, path_to_dev_pyworkbooks)

This could be important since 3rd party code may rely on sys.path documentation conformance:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

Storing and Retrieving ArrayList values from hashmap

You can use like this(Though the random number generator logic is not upto the mark)

public class WorkSheet {
    HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();

public static void main(String args[]) {
    WorkSheet test = new WorkSheet();
    test.inputData("mango", 5);
    test.inputData("apple", 2);
    test.inputData("grapes", 2);
    test.inputData("peach", 3);
    test.displayData();

}
public void displayData(){
    for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
        System.out.print(entry.getKey()+" | ");
        for(int fruitNo : entry.getValue()){
            System.out.print(fruitNo+" ");
        }
        System.out.println();
    }
}
public void inputData(String name ,int number) {
    Random rndData = new Random();
    ArrayList<Integer> fruit = new ArrayList<Integer>();
    for(int i=0 ; i<number ; i++){
        fruit.add(rndData.nextInt(10));
    }
    map.put(name, fruit);
}
}

OUTPUT

grapes | 7 5 
apple | 9 5 
peach | 5 5 8 
mango | 4 7 1 5 5 

<div style display="none" > inside a table not working

simply change <div> to <tbody>

<table id="authenticationSetting" style="display: none">
  <tbody id="authenticationOuterIdentityBlock" style="display: none;">
    <tr>
      <td class="orionSummaryHeader">
        <orion:message key="policy.wifi.enterprise.authentication.outeridentitity" />:</td>
      <td class="orionSummaryColumn">
        <orion:textbox id="authenticationOuterIdentity" size="30" />
      </td>
    </tr>
  </tbody>
</table>

How To: Execute command line in C#, get STD OUT results

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "YOURBATCHFILE.bat";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

Code is from MSDN.

Get the latest record from mongodb collection

php7.1 mongoDB:
$data = $collection->findOne([],['sort' => ['_id' => -1],'projection' => ['_id' => 1]]);

CMake is not able to find BOOST libraries

Long answer to short, if you install boost in custom path, all header files must in ${path}/boost/.

if you want to konw why cmake can't find the requested Boost libraries after you have set BOOST_ROOT/BOOST_INCLUDEDIR, you can check cmake install location path_to_cmake/share/cmake-xxx/Modules/FindBoost.

cmake which will find Boost_INCLUDE_DIR in boost/config.hpp in BOOST_ROOT. That means your boost header file must in ${path}/boost/, any other format (such as ${path}/boost-x.y.z) will not be suitable for find_package in CMakeLists.txt.

Eclipse projects not showing up after placing project files in workspace/projects

I have tried many of the option suggested but at last importing project in new workspace solved my problem.

I think there is some problem in metadata files in old workspace.

What do the crossed style properties in Google Chrome devtools mean?

On a side note. If you are using @media queries (such as @media screen (max-width:500px)) pay particular attention to applying @media query AFTER you are done with normal styles. Because @media query will be crossed out (even though it is more specific) if followed by css that manipulates the same elements. Example:

@media (max-width:750px){
#buy-box {width: 300px;}
}

#buy-box{
width:500px;
}

** width will be 500px and 300px will be crossed out in Developer Tools. **

#buy-box{
width:500px;
}

@media (max-width:750px){
#buy-box {width: 300px;}
}

** width will be 300px and 500px will be crossed out **

List all files in one directory PHP

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";
        }
    }

    closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.

How can I list all foreign keys referencing a given table in SQL Server?

SELECT
OBJECT_NAME(parent_object_id) 'Parent table',
c.NAME 'Parent column name',
OBJECT_NAME(referenced_object_id) 'Referenced table',
cref.NAME 'Referenced column name'
FROM 
sys.foreign_key_columns fkc 
INNER JOIN 
sys.columns c 
   ON fkc.parent_column_id = c.column_id 
      AND fkc.parent_object_id = c.object_id
INNER JOIN 
sys.columns cref 
   ON fkc.referenced_column_id = cref.column_id 
      AND fkc.referenced_object_id = cref.object_id  where   OBJECT_NAME(parent_object_id) = 'tablename'

If you want to get the foreign key relation of all the tables exclude the where clause else write your tablename instead of tablename

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

I do the "in clause" query with spring jdbc like this:

String sql = "SELECT bg.goodsid FROM beiker_goods bg WHERE bg.goodsid IN (:goodsid)";

List ids = Arrays.asList(new Integer[]{12496,12497,12498,12499});
Map<String, List> paramMap = Collections.singletonMap("goodsid", ids);
NamedParameterJdbcTemplate template = 
    new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());

List<Long> list = template.queryForList(sql, paramMap, Long.class);

What does 'synchronized' mean?

What the other answers are missing is one important aspect: memory barriers. Thread synchronization basically consists of two parts: serialization and visibility. I advise everyone to google for "jvm memory barrier", as it is a non-trivial and extremely important topic (if you modify shared data accessed by multiple threads). Having done that, I advise looking at java.util.concurrent package's classes that help to avoid using explicit synchronization, which in turn helps keeping programs simple and efficient, maybe even preventing deadlocks.

One such example is ConcurrentLinkedDeque. Together with the command pattern it allows to create highly efficient worker threads by stuffing the commands into the concurrent queue -- no explicit synchronization needed, no deadlocks possible, no explicit sleep() necessary, just poll the queue by calling take().

In short: "memory synchronization" happens implicitly when you start a thread, a thread ends, you read a volatile variable, you unlock a monitor (leave a synchronized block/function) etc. This "synchronization" affects (in a sense "flushes") all writes done before that particular action. In the case of the aforementioned ConcurrentLinkedDeque, the documentation "says":

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a ConcurrentLinkedDeque happen-before actions subsequent to the access or removal of that element from the ConcurrentLinkedDeque in another thread.

This implicit behavior is a somewhat pernicious aspect because most Java programmers without much experience will just take a lot as given because of it. And then suddenly stumble over this thread after Java isn't doing what it is "supposed" to do in production where there is a different work load -- and it's pretty hard to test concurrency issues.

Identifier is undefined

You may also be missing using namespace std;

Difference of two date time in sql server

I can mention four important functions of MS SQL Server that can be very useful:

1) The function DATEDIFF() is responsible to calculate differences between two dates, the result could be "year quarter month dayofyear day week hour minute second millisecond microsecond nanosecond", specified on the first parameter (datepart):

select datediff(day,'1997-10-07','2011-09-11')

2) You can use the function GETDATE() to get the actual time and calculate differences of some date and actual date:

select datediff(day,'1997-10-07', getdate() )

3) Another important function is DATEADD(), used to convert some value in datetime using the same datepart of the datediff, that you can add (with positive values) or substract (with negative values) to one base date:

select DATEADD(day,  45, getdate()) -- actual datetime adding 45 days
select DATEADD(  s,-638, getdate()) -- actual datetime subtracting 10 minutes and 38 seconds

4) The function CONVERT() was made to format the date like you need, it is not parametric function, but you can use part of the result to format the result like you need:

select convert(  char(8), getdate() ,   8) -- part hh:mm:ss of actual datetime
select convert(  varchar, getdate() , 112) -- yyyymmdd
select convert( char(10), getdate() ,  20) -- yyyy-mm-dd limited by 10 characters

DATETIME cold be calculated in seconds and one interesting result mixing these four function is to show a formated difference um hours, minutes and seconds (hh:mm:ss) between two dates:

declare  @date1 datetime, @date2 datetime
set @date1=DATEADD(s,-638,getdate())
set @date2=GETDATE()

select convert(char(8),dateadd(s,datediff(s,@date1,@date2),'1900-1-1'),8)

... the result is 00:10:38 (638s = 600s + 38s = 10 minutes and 38 seconds)

Another example:

select distinct convert(char(8),dateadd(s,datediff(s, CRDATE , GETDATE() ),'1900-1-1'),8) from sysobjects order by 1

Set TextView text from html-formatted string resource in XML

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old:

When using String resources in Android, you just have to call getString(...) from Java code or use android:text="@string/..." in your layout XML.

Even if you want to use HTML markup in your Strings, you don't have to change a lot:

The only characters that you need to escape in your String resources are:

  • double quotation mark: " becomes \"
  • single quotation mark: ' becomes \'
  • ampersand: & becomes &#38; or &amp;

That means you can add your HTML markup without escaping the tags:

<string name="my_string"><b>Hello World!</b> This is an example.</string>

However, to be sure, you should only use <b>, <i> and <u> as they are listed in the documentation.

If you want to use your HTML strings from XML, just keep on using android:text="@string/...", it will work fine.

The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(...) instead of getString(...) now, as the former keeps the style and the latter will just strip it off.

It's as easy as that. No CDATA, no Html.fromHtml(...).

You will only need Html.fromHtml(...) if you did encode your special characters in HTML markup. Use it with getString(...) then. This can be necessary if you want to pass the String to String.format(...).

This is all described in the docs as well.

Edit:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...).

See the following graphic for a comparison:

enter image description here

Multiple submit buttons in the same form calling different Servlets

There are several ways to achieve this.

Probably the easiest would be to use JavaScript to change the form's action.

<input type="submit" value="SecondServlet" onclick="form.action='SecondServlet';">

But this of course won't work when the enduser has JS disabled (mobile browsers, screenreaders, etc).


Another way is to put the second button in a different form, which may or may not be what you need, depending on the concrete functional requirement, which is not clear from the question at all.

<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" value="FirstServlet">
</form>
<form action="SecondServlet" method="Post">
    <input type="submit"value="SecondServlet">
</form>

Note that a form would on submit only send the input data contained in the very same form, not in the other form.


Again another way is to just create another single entry point servlet which delegates further to the right servlets (or preferably, the right business actions) depending on the button pressed (which is by itself available as a request parameter by its name):

<form action="MainServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" name="action" value="FirstServlet">
    <input type="submit" name="action" value="SecondServlet">
</form>

with the following in MainServlet

String action = request.getParameter("action");

if ("FirstServlet".equals(action)) {
    // Invoke FirstServlet's job here.
} else if ("SecondServlet".equals(action)) {
    // Invoke SecondServlet's job here.
}

This is only not very i18n/maintenance friendly. What if you need to show buttons in a different language or change the button values while forgetting to take the servlet code into account?


A slight change is to give the buttons its own fixed and unique name, so that its presence as request parameter could be checked instead of its value which would be sensitive to i18n/maintenance:

<form action="MainServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" name="first" value="FirstServlet">
    <input type="submit" name="second" value="SecondServlet">
</form>

with the following in MainServlet

if (request.getParameter("first") != null) {
    // Invoke FirstServlet's job here.
} else if (request.getParameter("second") != null) {
    // Invoke SecondServlet's job here.
}

Last way would be to just use a MVC framework like JSF so that you can directly bind javabean methods to buttons, but that would require drastic changes to your existing code.

<h:form>
    Last Name: <h:inputText value="#{bean.lastName}" size="20" />
    <br/><br/>
    <h:commandButton value="First" action="#{bean.first}" />
    <h:commandButton value="Second" action="#{bean.Second}" />
</h:form>

with just the following javabean instead of a servlet

@ManagedBean
@RequestScoped
public class Bean {

    private String lastName; // +getter+setter

    public void first() {
        // Invoke original FirstServlet's job here.
    }

    public void second() {
        // Invoke original SecondServlet's job here.
    }

}

Using column alias in WHERE clause of MySQL query produces an error

Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. For example, the following query is illegal:

SELECT id, COUNT(*) AS cnt FROM tbl_name WHERE cnt > 0 GROUP BY id;

mongodb count num of distinct values per field/key

With MongoDb 3.4.4 and newer, you can leverage the use of $arrayToObject operator and a $replaceRoot pipeline to get the counts.

For example, suppose you have a collection of users with different roles and you would like to calculate the distinct counts of the roles. You would need to run the following aggregate pipeline:

db.users.aggregate([
    { "$group": {
        "_id": { "$toLower": "$role" },
        "count": { "$sum": 1 }
    } },
    { "$group": {
        "_id": null,
        "counts": {
            "$push": { "k": "$_id", "v": "$count" }
        }
    } },
    { "$replaceRoot": {
        "newRoot": { "$arrayToObject": "$counts" }
    } }    
])

Example Output

{
    "user" : 67,
    "superuser" : 5,
    "admin" : 4,
    "moderator" : 12
}

Array of Matrices in MATLAB

Use cell arrays. This has an advantage over 3D arrays in that it does not require a contiguous memory space to store all the matrices. In fact, each matrix can be stored in a different space in memory, which will save you from Out-of-Memory errors if your free memory is fragmented. Here is a sample function to create your matrices in a cell array:

function result = createArrays(nArrays, arraySize)
    result = cell(1, nArrays);
    for i = 1 : nArrays
        result{i} = zeros(arraySize);
    end
end

To use it:

myArray = createArrays(requiredNumberOfArrays, [500 800]);

And to access your elements:

myArray{1}(2,3) = 10;

If you can't know the number of matrices in advance, you could simply use MATLAB's dynamic indexing to make the array as large as you need. The performance overhead will be proportional to the size of the cell array, and is not affected by the size of the matrices themselves. For example:

myArray{1} = zeros(500, 800);
if twoRequired, myArray{2} = zeros(500, 800); end

Form inside a form, is that alright?

Nested forms are not supported and are not part of the w3c standard ( as many of you have stated ).

However HTML5 adds support for inputs that don't have to be descendants of any form, but can be submitted in several forms - by using the "form" attribute. This doesn't exactly allow nested forms, but by using this method, you can simulate nested forms.

The value of the "form" attribute must be id of the form, or in case of multiple forms, separate form id's with space.

You can read more here

How do I configure php to enable pdo and include mysqli on CentOS?

mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64

You may need to try the following

yum install php-mysql-5.3.3-40.el6_6.x86_64

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

OSX and Android Studio version:

CMD+ [ and CMD+ ]

to move to the previous carret location.

How to iterate a table rows with JQuery and access some cell values?

$("tr.item").each(function() {
  $this = $(this);
  var value = $this.find("span.value").html();
  var quantity = $this.find("input.quantity").val();
});

git: patch does not apply

WARNING: This command can remove old lost commits PERMANENTLY. Make a copy of your entire repository before attempting this.

I have found this link

I have no idea why this works but I tried many work arounds and this is the only one that worked for me. In short, run the three commands below:

git fsck --full
git reflog expire --expire=now --all
git gc --prune=now

How to iterate through property names of Javascript object?

In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

Object.getOwnPropertyNames ( obj )

and another method Object.keys, which returns an array containing the names of all of the given object's own enumerable properties.

Object.keys( obj )

I used forEach to list values and keys in obj, same as for (var key in obj) ..

Object.keys(obj).forEach(function (key) {
      console.log( key , obj[key] );
});

This all are new features in ECMAScript , the mothods getOwnPropertyNames, keys won't supports old browser's.

How do I enable saving of filled-in fields on a PDF form?

Open your PDF in Google Chrome. Edit the PDF as you want. Hit ctrl + p. Save as PDF to your desktop.

Emulate Samsung Galaxy Tab

UPDATED:
Matt provided a great link on how to add emulators for all Samsung devices.

OLD:
To get the official Samsung Galaxy Tab emulator do the following:

  1. Open the Android SDK and AVD Manager
  2. Click on Available packages
  3. Expand the Third party Add-ons. There you will see Samsung Electronics add-ons.
  4. Once the add-on is installed create a new emulator. Under Target you will see the new Samsung Tab settings, select that.

That's it!

Complex numbers usage in python

The following example for complex numbers should be self explanatory including the error message at the end

>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>> 

How do you revert to a specific tag in Git?

You can use git checkout.

I tried the accepted solution but got an error, warning: refname '<tagname>' is ambiguous'

But as the answer states, tags do behave like a pointer to a commit, so as you would with a commit hash, you can just checkout the tag. The only difference is you preface it with tags/:

git checkout tags/<tagname>

How to implement 2D vector array?

If you know the (maximum) number of rows and columns beforehand, you can use resize() to initialize a vector of vectors and then modify (and access) elements with operator[]. Example:

int no_of_cols = 5;
int no_of_rows = 10;
int initial_value = 0;

std::vector<std::vector<int>> matrix;
matrix.resize(no_of_rows, std::vector<int>(no_of_cols, initial_value));

// Read from matrix.
int value = matrix[1][2];

// Save to matrix.
matrix[3][1] = 5;

Another possibility is to use just one vector and split the id in several variables, access like vector[(row * columns) + column].

Cannot make file java.io.IOException: No such file or directory

Print the full file name out or step through in a debugger. When I get confused by errors like this, it means that my assumptions and expectations don't match reality. Make sure you can see what the path is; it'll help you figure out where you've gone wrong.

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

jQuery(document).ready(function(){
   jQuery(".head h3").html('Public Offers');
});

SQL selecting rows by most recent date with two unique columns

So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".

Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row

SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( 
    SELECT chargeId,MAX(serviceMonth) AS serviceMonth
    FROM invoice
    GROUP BY chargeId) x 
    JOIN invoice t ON x.chargeId =t.chargeId
    AND x.serviceMonth = t.serviceMonth

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

I encountered similar problem recently. The fix is to set the display property of the li items in the ordered list to list-item, and not display block, and ensure that the display property of ol is not list-item. i.e

li { display: list-item;}

With this, the html parser sees all li as the list item and assign the appropriate value to it, and sees the ol, as an inline-block or block element based on your settings, and doesn't try to assign any count value to it.

How to install pip for Python 3.6 on Ubuntu 16.10?

Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.

If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:

sudo add-apt-repository ppa:jonathonf/python-3.6  # (only for 16.04 LTS)

Then, run the following (this works out-of-the-box on 16.10 and 17.04):

sudo apt update
sudo apt install python3.6
sudo apt install python3.6-dev
sudo apt install python3.6-venv
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3

# Do this only if you want python3 to be the default Python
# instead of python2 (may be dangerous, esp. before 2020):
# sudo ln -s /usr/bin/python3.6 /usr/local/bin/python

When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1 (or a more recent version of Python 3.6):

python --version   # (this will reflect your choice, see above)
python3 --version
$(head -1 `which pip` | tail -c +3) --version
$(head -1 `which pip3` | tail -c +3) --version

AngularJS : Why ng-bind is better than {{}} in angular?

Visibility:

While your angularjs is bootstrapping, the user might see your placed brackets in the html. This can be handled with ng-cloak. But for me this is a workaround, that I don't need to use, if I use ng-bind.


Performance:

The {{}} is much slower.

This ng-bind is a directive and will place a watcher on the passed variable. So the ng-bind will only apply, when the passed value does actually change.

The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary.


I am currently building a big single page app (~500 bindings per view). Changing from {{}} to strict ng-bind did save us about 20% in every scope.$digest.


Suggestion:

If you use a translation module such as angular-translate, always prefer directives before brackets annotation.

{{'WELCOME'|translate}} => <span ng-translate="WELCOME"></span>

If you need a filter function, better go for a directive, that actually just uses your custom filter. Documentation for $filter service


UPDATE 28.11.2014 (but maybe off the topic):

In Angular 1.3x the bindonce functionality was introduced. Therefore you can bind the value of an expression/attribute once (will be bound when != 'undefined').

This is useful when you don't expect your binding to change.

Usage: Place :: before your binding:

<ul>  
  <li ng-repeat="item in ::items">{{item}}</li>
</ul>  
<a-directive name="::item">
<span data-ng-bind="::value"></span>

Example:

ng-repeat to output some data in the table, with multiple bindings per row. Translation-bindings, filter outputs, which get executed in every scope digest.

Resolve Javascript Promise outside function scope

Yes, you can. By using the CustomEvent API for the browser environment. And using an event emitter project in node.js environments. Since the snippet in the question is for the browser environment, here is a working example for the same.

_x000D_
_x000D_
function myPromiseReturningFunction(){_x000D_
  return new Promise(resolve => {_x000D_
    window.addEventListener("myCustomEvent", (event) => {_x000D_
       resolve(event.detail);_x000D_
    }) _x000D_
  })_x000D_
}_x000D_
_x000D_
_x000D_
myPromiseReturningFunction().then(result => {_x000D_
   alert(result)_x000D_
})_x000D_
_x000D_
document.getElementById("p").addEventListener("click", () => {_x000D_
   window.dispatchEvent(new CustomEvent("myCustomEvent", {detail : "It works!"}))_x000D_
})
_x000D_
<p id="p"> Click me </p>
_x000D_
_x000D_
_x000D_

I hope this answer is useful!

Iif equivalent in C#

It's limited in that you can't put statements in there. You can only put values(or things that return/evaluate to values), to return

This works ('a' is a static int within class Blah)

Blah.a=Blah.a<5?1:8;

(round brackets are impicitly between the equals and the question mark).

This doesn't work.

Blah.a = Blah.a < 4 ? Console.WriteLine("asdf") : Console.WriteLine("34er");
or
Blah.a = Blah.a < 4 ? MessageBox.Show("asdf") : MessageBox.Show("34er");

So you can only use the c# ternary operator for returning values. So it's not quite like a shortened form of an if. Javascript and perhaps some other languages let you put statements in there.

Angular 4 - Observable catch error

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())

How to Logout of an Application Where I Used OAuth2 To Login With Google?

For me, it works (java - android)

void RevokeAcess()
{
    try{
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/revoke?token="+ACCESS_TOKEN);
    org.apache.http.HttpResponse response = client.execute(post);
    }
    catch(IOException e)
    {
    }
    CookieManager.getInstance().removeAllCookie(); // this is clear the cookies which tends to same user in android web view
}

You have to call this function in AsyncTask in android

How to remove/delete a large file from commit history in Git repository?

When you run into this problem, git rm will not suffice, as git remembers that the file existed once in our history, and thus will keep a reference to it.

To make things worse, rebasing is not easy either, because any references to the blob will prevent git garbage collector from cleaning up the space. This includes remote references and reflog references.

I put together git forget-blob, a little script that tries removing all these references, and then uses git filter-branch to rewrite every commit in the branch.

Once your blob is completely unreferenced, git gc will get rid of it

The usage is pretty simple git forget-blob file-to-forget. You can get more info here

https://ownyourbits.com/2017/01/18/completely-remove-a-file-from-a-git-repository-with-git-forget-blob/

I put this together thanks to the answers from Stack Overflow and some blog entries. Credits to them!

javascript return true or return false when and how to use it?

returning true or false indicates that whether execution should continue or stop right there. So just an example

<input type="button" onclick="return func();" />

Now if func() is defined like this

function func()
{
 // do something
return false;
}

the click event will never get executed. On the contrary if return true is written then the click event will always be executed.

CSS - center two images in css side by side

Flexbox can do this with just two css rules on a surrounding div.

_x000D_
_x000D_
.social-media{_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
}
_x000D_
<div class="social-media">_x000D_
<a href="mailto:[email protected]">_x000D_
<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">_x000D_
<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

iPhone UILabel text soft shadow

In Swift 3, you can create an extension:

import UIKit

extension UILabel {
    func shadow() {
        self.layer.shadowColor = self.textColor.cgColor
        self.layer.shadowOffset = CGSize.zero
        self.layer.shadowRadius = 3.0
        self.layer.shadowOpacity = 0.5
        self.layer.masksToBounds = false
        self.layer.shouldRasterize = true
    }
}

and use it via:

label.shadow()

Pandas Merge - How to avoid duplicating columns

You can work out the columns that are only in one DataFrame and use this to select a subset of columns in the merge.

cols_to_use = df2.columns.difference(df.columns)

Then perform the merge (note this is an index object but it has a handy tolist() method).

dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer')

This will avoid any columns clashing in the merge.

Add a thousands separator to a total with Javascript or jQuery?

Consider this:

function group1k(s) {
    return (""+s)
        .replace(/(\d+)(\d{3})(\d{3})$/  ,"$1 $2 $3" )
        .replace(/(\d+)(\d{3})$/         ,"$1 $2"    )
        .replace(/(\d+)(\d{3})(\d{3})\./ ,"$1 $2 $3.")
        .replace(/(\d+)(\d{3})\./        ,"$1 $2."   )
    ;
}

It's a quick solution for anything under 999.999.999, which is usually enough. I know the drawbacks and I'm not saying this is the ultimate weapon - but it's just as fast as the others above and I find this one more readable. If you don't need decimals you can simplify it even more:

function group1k(s) {
    return (""+s)
        .replace(/(\d+)(\d{3})(\d{3})$/ ,"$1 $2 $3")
        .replace(/(\d+)(\d{3})$/        ,"$1 $2"   )
    ;
}

Isn't it handy.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How to clear File Input

this code works for all browsers and all inputs.

$('#your_target_input').attr('value', '');

How to remove the left part of a string?

Try Following code

if line.startswith("Path="): return line[5:]

Creating SVG graphics using Javascript?

To do it cross-browser, I strongly recommend RaphaelJS. It has a hell of a good API and does VML in IE, that can't understand SVG.

What's the difference between "&nbsp;" and " "?

&nbsp; should be handled as a whitespace.

&nbsp;&nbsp; should be handled as two whitespaces

' ' can be handled as a non interesting whitespace

' ' + ' ' can be handled as a single ' '

How to run a Command Prompt command with Visual Basic code?

Yes. You can use Process.Start to launch an executable, including a console application.

If you need to read the output from the application, you may need to read from it's StandardOutput stream in order to get anything printed from the application you launch.

Angular ng-class if else

You can use the ternary operator notation:

<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">

How to get a parent element to appear above child

Set a negative z-index for the child, and remove the one set on the parent.

_x000D_
_x000D_
.parent {_x000D_
    position: relative;_x000D_
    width: 350px;_x000D_
    height: 150px;_x000D_
    background: red;_x000D_
    border: solid 1px #000;_x000D_
}_x000D_
.parent2 {_x000D_
    position: relative;_x000D_
    width: 350px;_x000D_
    height: 40px;_x000D_
    background: red;_x000D_
    border: solid 1px #000;_x000D_
}_x000D_
.child {_x000D_
    position: relative;_x000D_
    background-color: blue;_x000D_
    height: 200px;_x000D_
}_x000D_
.wrapper {_x000D_
    position: relative;_x000D_
    background: green;_x000D_
    height: 350px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="parent">parent 1 parent 1_x000D_
        <div class="child">child child child</div>_x000D_
    </div>_x000D_
    <div class="parent2">parent 2 parent 2_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/uov5h84f/

Spring MVC Missing URI template variable

I got this error for a stupid mistake, the variable name in the @PathVariable wasn't matching the one in the @RequestMapping

For example

@RequestMapping(value = "/whatever/{**contentId**}", method = RequestMethod.POST)
public … method(@PathVariable Integer **contentID**){
}

It may help others

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

As a hack, you could consider having a special handling on the client side, converting 'Null' string to something that will never occur, for example, XXNULLXX and converting back on the server.

It is not pretty, but it may solve the issue for such a boundary case.

Create directory if it does not exist

When you specify the -Force flag, PowerShell will not complain if the folder already exists.

One-liner:

Get-ChildItem D:\TopDirec\SubDirec\Project* | `
  %{ Get-ChildItem $_.FullName -Filter Revision* } | `
  %{ New-Item -ItemType Directory -Force -Path (Join-Path $_.FullName "Reports") }

BTW, for scheduling the task please check out this link: Scheduling Background Jobs.

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

I don't think other answers explained the key part: why "COUNT(*)" returns more than one result?

I just encountered the same issue today, and what I found out is that if you have another class extending the target mapped class (here "CustomerData"), Hibernate will do this magic.

Hope this will save some time for other unfortunate guys.

React: Expected an assignment or function call and instead saw an expression

Possible way is (sure you can change array declaration to getting from db or another external resource):

const MyPosts = () => {

  let postsRawData = [
    { id: 1, text: 'Post 1', likesCount: '1' },
    { id: 2, text: 'Post 2', likesCount: '231' },
    { id: 3, text: 'Post 3', likesCount: '547' }
  ];

  const postsItems = []
  for (const [key, value] of postsRawData.entries()) {
    postsItems.push(<Post text={value.text} likesCount={value.likesCount} />)
  }

  return (
      <div className={css.posts}>Posts:
          {postsItems}
      </div>
  )
}

Swift apply .uppercaseString to only the first letter of a string

In swift 5

https://www.hackingwithswift.com/example-code/strings/how-to-capitalize-the-first-letter-of-a-string

extension String {
    func capitalizingFirstLetter() -> String {
        return prefix(1).capitalized + dropFirst()
    }

    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()
    }
}

use with your string

let test = "the rain in Spain"
print(test.capitalizingFirstLetter())

Android: Pass data(extras) to a fragment

Two things. First I don't think you are adding the data that you want to pass to the fragment correctly. What you need to pass to the fragment is a bundle, not an intent. For example if I wanted send an int value to a fragment I would create a bundle, put the int into that bundle, and then set that bundle as an argument to be used when the fragment was created.

Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Second to retrieve that information you need to get the arguments sent to the fragment. You then extract the value based on the key you identified it with. For example in your fragment:

Bundle bundle = this.getArguments();
if (bundle != null) {
    int i = bundle.getInt(key, defaulValue);
}

What you are getting changes depending on what you put. Also the default value is usually null but does not need to be. It depends on if you set a default value for that argument.

Lastly I do not think you can do this in onCreateView. I think you must retrieve this data within your fragment's onActivityCreated method. My reasoning is as follows. onActivityCreated runs after the underlying activity has finished its own onCreate method. If you are placing the information you wish to retrieve within the bundle durring your activity's onCreate method, it will not exist during your fragment's onCreateView. Try using this in onActivityCreated and just update your ListView contents later.

when exactly are we supposed to use "public static final String"?

  1. Static means..You can use it without instantiate of the class or using any object.
  2. final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:

      public class StringTest { 
               static final String str = "Hello"; 
      public static void main(String args[]) { 
               // str = "world"; // gives error 
               System.out.println(str); // called without the help of an object                       
               System.out.println(StringTest.str);// called with class name  
                 } 
             } 
    

Thanks

When would you use the different git merge strategies?

As the answers above are not showing all strategy details. For example, some answer is missing the details about the import resolve option and the recursive which has many sub options as ours, theirs, patience, renormalize, etc.

Therefore, I would recommend to visit the official git documentation which explains all the possible features features:

https://git-scm.com/docs/merge-strategies

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

enter image description here

Considering the particular column Amount in the above table is of integer type. The following would be a solution :

df['Amount'] = df.Amount.fillna(0).astype(int)

Similarly, you can fill it with various data types like float, str and so on.

In particular, I would consider datatype to compare various values of the same column.

How to set column widths to a jQuery datatable?

In java script calculate width using following code

var scrollX = $(window).width()*58/100;
var oTable = $('#reqAllRequestsTable').dataTable({
    "sScrollX": scrollX
    } );

/usr/bin/ld: cannot find

You need to add -L/opt/lib to tell ld to look there for shared objects.

Python if not == vs if !=

Using dis to look at the bytecode generated for the two versions:

not ==

  4           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               2 (==)
              9 UNARY_NOT           
             10 RETURN_VALUE   

!=

  4           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               3 (!=)
              9 RETURN_VALUE   

The latter has fewer operations, and is therefore likely to be slightly more efficient.


It was pointed out in the commments (thanks, @Quincunx) that where you have if foo != bar vs. if not foo == bar the number of operations is exactly the same, it's just that the COMPARE_OP changes and POP_JUMP_IF_TRUE switches to POP_JUMP_IF_FALSE:

not ==:

  2           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               2 (==)
              9 POP_JUMP_IF_TRUE        16

!=

  2           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               3 (!=)
              9 POP_JUMP_IF_FALSE       16

In this case, unless there was a difference in the amount of work required for each comparison, it's unlikely you'd see any performance difference at all.


However, note that the two versions won't always be logically identical, as it will depend on the implementations of __eq__ and __ne__ for the objects in question. Per the data model documentation:

There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false.

For example:

>>> class Dummy(object):
    def __eq__(self, other):
        return True
    def __ne__(self, other):
        return True


>>> not Dummy() == Dummy()
False
>>> Dummy() != Dummy()
True

Finally, and perhaps most importantly: in general, where the two are logically identical, x != y is much more readable than not x == y.

"git rebase origin" vs."git rebase origin/master"

Here's a better option:

git remote set-head -a origin

From the documentation:

With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.

This has actually been around quite a while (since v1.6.3); not sure how I missed it!

Can Twitter Bootstrap alerts fade in as well as out?

I got this way to close fading my Alert after 3 seconds. Hope it will be useful.

    setTimeout(function(){
    $('.alert').fadeTo("slow", 0.1, function(){
        $('.alert').alert('close')
    });     
    }, 3000)

Redirect in Spring MVC

For completing the answers, Spring MVC uses viewResolver(for example, as axtavt metionned, InternalResourceViewResolver) to get the specific view. Therefore the first step is making sure that a viewResolver is configured.

Secondly, you should pay attention to the url of redirection(redirect or forward). A url starting with "/" means that it's a url absolute in the application. As Jigar says,

return "redirect:/index.html";  

should work. If your view locates in the root of the application, Spring can find it. If a url without a "/", such as that in your question, it means a url relative. It explains why it worked before and don't work now. If your page calling "redirect" locates in the root by chance, it works. If not, Spring can't find the view and it doesn't work.

Here is the source code of the method of RedirectView of Spring

protected void renderMergedOutputModel(  
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)  
throws IOException {  
  // Prepare target URL.  
  StringBuilder targetUrl = new StringBuilder();  
  if (this.contextRelative && getUrl().startsWith("/")) {  
    // Do not apply context path to relative URLs.  
    targetUrl.append(request.getContextPath());  
  }  
  targetUrl.append(getUrl());  

  // ...  

  sendRedirect(request, response, targetUrl.toString(), this.http10Compatible);  
}  

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

Can't install via pip because of egg_info error

virtualenv is a tool to create isolated Python environments.

you will need to add the following to fix command python setup.py egg_info failed with error code 1, so inside your requirements.txt add this:

virtualenv==12.0.7

How can I save multiple documents concurrently in Mongoose/Node.js?

Use insertMany function to insert many documents. This sends only one operation to the server and Mongoose validates all the documents before hitting the mongo server. By default Mongoose inserts item in the order they exist in the array. If you are ok with not maintaining any order then set ordered:false.

Important - Error handling:

When ordered:true validation and error handling happens in a group means if one fails everything will fail.

When ordered:false validation and error handling happens individually and operation will be continued. Error will be reported back in an array of errors.

UPDATE and REPLACE part of a string

UPDATE table_name
SET field_name = '0'
WHERE field_name IS Null

Why am I getting string does not name a type Error?

Try a using namespace std; at the top of game.h or use the fully-qualified std::string instead of string.

The namespace in game.cpp is after the header is included.

How to use && in EL boolean expressions in Facelets?

Facelets is a XML based view technology. The & is a special character in XML representing the start of an entity like &amp; which ends with the ; character. You'd need to either escape it, which is ugly:

rendered="#{beanA.prompt == true &amp;&amp; beanB.currentBase != null}"

or to use the and keyword instead, which is preferred as to readability and maintainability:

rendered="#{beanA.prompt == true and beanB.currentBase != null}"

See also:


Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true:

rendered="#{beanA.prompt and beanB.currentBase != null}"

Adding delay between execution of two following lines

This line calls the selector secondMethod after 3 seconds:

[self performSelector:@selector(secondMethod) withObject:nil afterDelay:3.0 ];

Use it on your second operation with your desired delay. If you have a lot of code, place it in its own method and call that method with performSelector:. It wont block the UI like sleep

Edit: If you do not want a second method you could add a category to be able to use blocks with performSelector:

@implementation NSObject (PerformBlockAfterDelay)

- (void)performBlock:(void (^)(void))block 
          afterDelay:(NSTimeInterval)delay
{
    block = [block copy];
    [self performSelector:@selector(fireBlockAfterDelay:) 
               withObject:block 
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block
{
    block();
}

@end

Or perhaps even cleaner:

void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
      dispatch_get_current_queue(), block);
}