Programs & Examples On #Pagerank

PageRank is a graph algorithm that assigns importance to nodes based on their links, and is named after its inventor - Larry Page. The algorithm is frequently applied to web graphs to calculate an importance of each node [url] in the graph.

What's the difference between xsd:include and xsd:import?

Another difference is that <import> allows importing by referring to another namespace. <include> only allows importing by referring to a URI of intended include schema. That is definitely another difference than inter-intra namespace importing.

For example, the xml schema validator may already know the locations of all schemas by namespace already. Especially considering that referring to XML namespaces by URI may be problematic on different systems where classpath:// means nothing, or where http:// isn't allowed, or where some URI doesn't point to the same thing as it does on another system.

Code sample of valid and invalid imports and includes:

Valid:

<xsd:import namespace="some/name/space"/>
<xsd:import schemaLocation="classpath://mine.xsd"/>

<xsd:include schemaLocation="classpath://mine.xsd"/>

Invalid:

<xsd:include namespace="some/name/space"/>

How can I override the OnBeforeUnload dialog and replace it with my own?

What about to use the specialized version of the "bind" command "one". Once the event handler executes the first time, it’s automatically removed as an event handler.

$(window).one("beforeunload", BeforeUnload);

How can I wait for a thread to finish with .NET?

Try this:

List<Thread> myThreads = new List<Thread>();

foreach (Thread curThread in myThreads)
{
    curThread.Start();
}

foreach (Thread curThread in myThreads)
{
    curThread.Join();
}

CSV new-line character seen in unquoted field error

For Mac OS X, save your CSV file in "Windows Comma Separated (.csv)" format.

Update data on a page without refreshing

In general, if you don't know how something works, look for an example which you can learn from.

For this problem, consider this DEMO

You can see loading content with AJAX is very easily accomplished with jQuery:

$(function(){
    // don't cache ajax or content won't be fresh
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";

    // load() functions
    var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
    $("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

// end  
});

Try to understand how this works and then try replicating it. Good luck.

You can find the corresponding tutorial HERE

Update

Right now the following event starts the ajax load function:

$("#loadbasic").click(function(){
        $("#result").html(ajax_load).load(loadUrl);
    });

You can also do this periodically: How to fire AJAX request Periodically?

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();

I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);) the content is updated.

You can also just load the data immediately:

$("#result").html(ajax_load).load(loadUrl);

Which has THIS corresponding demo.

Removing double quotes from a string in Java

Use replace method of string like the following way:

String x="\"abcd";
String z=x.replace("\"", "");
System.out.println(z);

Output:

abcd

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

For Windows users:

Set-ExecutionPolicy RemoteSigned -scope CurrentUser
iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
scoop install gradle

Cannot uninstall angular-cli

I had the same problem. This doesn't work:

npm uninstall -g angular/cli
npm cache clean

instead use:

npm uninstall -g @ angular/cli

How to make a simple collection view with Swift

Delegates and Datasources of UICollectionView

//MARK: UICollectionViewDataSource

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)
    configureCell(cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.blackColor()


    //Customise your cell

}

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", forIndexPath: indexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
      // When user selects the cell
}

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
     // When user deselects the cell
}

Using ExcelDataReader to read Excel data starting from a particular cell

If you are using ExcelDataReader 3+ you will find that there isn't any method for AsDataSet() for your reader object, You need to also install another package for ExcelDataReader.DataSet, then you can use the AsDataSet() method.
Also there is not a property for IsFirstRowAsColumnNames instead you need to set it inside of ExcelDataSetConfiguration.

Example:

using (var stream = File.Open(originalFileName, FileMode.Open, FileAccess.Read))
{
    IExcelDataReader reader;

    // Create Reader - old until 3.4+
    ////var file = new FileInfo(originalFileName);
    ////if (file.Extension.Equals(".xls"))
    ////    reader = ExcelDataReader.ExcelReaderFactory.CreateBinaryReader(stream);
    ////else if (file.Extension.Equals(".xlsx"))
    ////    reader = ExcelDataReader.ExcelReaderFactory.CreateOpenXmlReader(stream);
    ////else
    ////    throw new Exception("Invalid FileName");
    // Or in 3.4+ you can only call this:
    reader = ExcelDataReader.ExcelReaderFactory.CreateReader(stream)

    //// reader.IsFirstRowAsColumnNames
    var conf = new ExcelDataSetConfiguration
    {
        ConfigureDataTable = _ => new ExcelDataTableConfiguration
        {
            UseHeaderRow = true 
        }
    };

    var dataSet = reader.AsDataSet(conf);

    // Now you can get data from each sheet by its index or its "name"
    var dataTable = dataSet.Tables[0];

    //...
}

You can find row number and column number of a cell reference like this:

var cellStr = "AB2"; // var cellStr = "A1";
var match = Regex.Match(cellStr, @"(?<col>[A-Z]+)(?<row>\d+)");
var colStr = match.Groups["col"].ToString();
var col = colStr.Select((t, i) => (colStr[i] - 64) * Math.Pow(26, colStr.Length - i - 1)).Sum();
var row = int.Parse(match.Groups["row"].ToString());

Now you can use some loops to read data from that cell like this:

for (var i = row; i < dataTable.Rows.Count; i++)
{
    for (var j = col; j < dataTable.Columns.Count; j++)
    {
        var data = dataTable.Rows[i][j];
    }
}

Update:

You can filter rows and columns of your Excel sheet at read time with this config:

var i = 0;
var conf = new ExcelDataSetConfiguration
{
    UseColumnDataType = true,
    ConfigureDataTable = _ => new ExcelDataTableConfiguration
    {
        FilterRow = rowReader => fromRow <= ++i - 1,
        FilterColumn = (rowReader, colIndex) => fromCol <= colIndex,
        UseHeaderRow = true
    }
};

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!

Example:

                     data
2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
                     data
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000

How to connect HTML Divs with Lines?

Definitely possible with any number of libraries and/or HTML5 technologies. You could possible hack something together in pure CSS by using something like the border-bottom property, but it would probably be horribly hacky.

If you're serious about this, you should take a look at a JS library for canvas drawing or SVG. For example, something like http://www.graphjs.org/ or http://jsdraw2dx.jsfiction.com/

Use dynamic variable names in JavaScript

2019

TL;DR

  • eval operator can run string expression in the context it called and return variables from that context;
  • literal object theoretically can do that by write:{[varName]}, but it blocked by definition.

So I come across this question and everyone here just play around without bringing a real solution. but @Axel Heider has a good approaching.

The solution is eval. almost most forgotten operator. ( think most one is with() )

eval operator can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamically return a variable's value in function's context.

example:

function exmaple1(){
   var a = 1, b = 2, default = 3;
   var name = 'a';
   return eval(name)
}

example1() // return 1


function example2(option){
  var a = 1, b = 2, defaultValue = 3;

  switch(option){
    case 'a': name = 'a'; break;
    case 'b': name = 'b'; break;
    default: name = 'defaultValue';
  }
  return eval (name);
}

example2('a') // return 1
example2('b') // return 2
example2() // return 3

Note that I always write explicitly the expression eval will run. To avoid unnecessary surprises in the code. eval is very strong But I'm sure you know that already

BTW, if it was legal we could use literal object to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid

functopn example( varName ){
    var var1 = 'foo', var2 ='bar'

    var capture = {[varName]}

}

example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`

missing private key in the distribution certificate on keychain

Just to shed some light on this.

After I deleted my p12 certificate from Keychain. I re-downloaded my own certificate from Apple developer portal.

I was only able to download the certificate. But to sign you need the private key as well. So you either:

  • export both private key and certificate from Keychain to get it.

  • Upload a Certificate Signing Request and generate new certificates

That certificate by itself has no value for signing purposes. My guess is that the private key is created by keychain the moment you 'request a certificate from a certificate authority' but isn't shown to you until you add its tying certificate.

Redirect from an HTML page

I would use both meta, and JavaScript code and would have a link just in case.

<!DOCTYPE HTML>
<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="refresh" content="0; url=http://example.com">
        <script type="text/javascript">
            window.location.href = "http://example.com"
        </script>
        <title>Page Redirection</title>
    </head>
    <body>
        <!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->
        If you are not redirected automatically, follow this <a href='http://example.com'>link to example</a>.
    </body>
</html>

For completeness, I think the best way, if possible, is to use server redirects, so send a 301 status code. This is easy to do via .htaccess files using Apache, or via numerous plugins using WordPress. I am sure there are also plugins for all the major content management systems. Also, cPanel has very easy configuration for 301 redirects if you have that installed on your server.

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

Install alone didn't work for me.

mvn deploy:deploy-file -Durl=file:///home/me/project/lib/ \
  -Dfile=target/jzmq-2.1.3-SNAPSHOT.jar -DgroupId=org.zeromq \  
  -DartifactId=zeromq -Dpackaging=jar -Dversion=2.1.3

Choice between vector::resize() and vector::reserve()

The two functions do vastly different things!

The resize() method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the size(), iteration will go over all those elements, push_back will insert after them and you can directly access them using the operator[].

The reserve() method only allocates memory, but leaves it uninitialized. It only affects capacity(), but size() will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.

So it depends on what you want. If you want an array of 1000 default items, use resize(). If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, use reserve().

EDIT: Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocate manually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it more efficiently than the manual way mentioned. The only case where reserve() makes sense is when you have reasonably precise estimate of the total size you'll need easily available in advance.

EDIT2: Ad question edit: If you have initial estimate, then reserve() that estimate. If it turns out to be not enough, just let the vector do it's thing.

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

Jquery UI datepicker. Disable array of Dates

If you also want to block Sundays (or other days) as well as the array of dates, I use this code:

jQuery(function($){

    var disabledDays = [
       "27-4-2016", "25-12-2016", "26-12-2016",
       "4-4-2017", "5-4-2017", "6-4-2017", "6-4-2016", "7-4-2017", "8-4-2017", "9-4-2017"
    ];

   //replace these with the id's of your datepickers
   $("#id-of-first-datepicker,#id-of-second-datepicker").datepicker({
      beforeShowDay: function(date){
         var day = date.getDay();
         var string = jQuery.datepicker.formatDate('d-m-yy', date);
         var isDisabled = ($.inArray(string, disabledDays) != -1);

         //day != 0 disables all Sundays
         return [day != 0 && !isDisabled];
      }
   });
});   

What data type to use for money in Java?

Java has Currency class that represents the ISO 4217 currency codes. BigDecimal is the best type for representing currency decimal values.

Joda Money has provided a library to represent money.

How to make a promise from setTimeout

Implementation:

// Promisify setTimeout
const pause = (ms, cb, ...args) =>
  new Promise((resolve, reject) => {
    setTimeout(async () => {
      try {
        resolve(await cb?.(...args))
      } catch (error) {
        reject(error)
      }
    }, ms)
  })

Tests:

// Test 1
pause(1000).then(() => console.log('called'))
// Test 2
pause(1000, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
// Test 3
pause(1000, () => {
  throw Error('foo')
}).catch(error => console.error(error))

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

error: expected unqualified-id before ‘.’ token //(struct)

You are trying to access the struct statically with a . instead of ::, nor are its members static. Either instantiate ReducedForm:

ReducedForm rf;
rf.iSimplifiedNumerator = 5;

or change the members to static like this:

struct ReducedForm
{
    static int iSimplifiedNumerator;
    static int iSimplifiedDenominator;
};

In the latter case, you must access the members with :: instead of . I highly doubt however that the latter is what you are going for ;)

Get all files and directories in specific path fast

Maybe it will be helpfull for you. You could use "DirectoryInfo.EnumerateFiles" method and handle UnauthorizedAccessException as you need.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        DirectoryInfo diTop = new DirectoryInfo(@"d:\");
        try
        {
            foreach (var fi in diTop.EnumerateFiles())
            {
                try
                {
                    // Display each file over 10 MB; 
                    if (fi.Length > 10000000)
                    {
                        Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
                    }
                }
                catch (UnauthorizedAccessException UnAuthTop)
                {
                    Console.WriteLine("{0}", UnAuthTop.Message);
                }
            }

            foreach (var di in diTop.EnumerateDirectories("*"))
            {
                try
                {
                    foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
                    {
                        try
                        {
                            // Display each file over 10 MB; 
                            if (fi.Length > 10000000)
                            {
                                Console.WriteLine("{0}\t\t{1}",  fi.FullName, fi.Length.ToString("N0"));
                            }
                        }
                        catch (UnauthorizedAccessException UnAuthFile)
                        {
                            Console.WriteLine("UnAuthFile: {0}", UnAuthFile.Message);
                        }
                    }
                }
                catch (UnauthorizedAccessException UnAuthSubDir)
                {
                    Console.WriteLine("UnAuthSubDir: {0}", UnAuthSubDir.Message);
                }
            }
        }
        catch (DirectoryNotFoundException DirNotFound)
        {
            Console.WriteLine("{0}", DirNotFound.Message);
        }
        catch (UnauthorizedAccessException UnAuthDir)
        {
            Console.WriteLine("UnAuthDir: {0}", UnAuthDir.Message);
        }
        catch (PathTooLongException LongPath)
        {
            Console.WriteLine("{0}", LongPath.Message);
        }
    }
}

ssh_exchange_identification: Connection closed by remote host under Git bash

You can get "ssh_exchange_identification: Connection closed by remote host" if your sshd service is not operational!

If you have access to the server check you have the sshd service running with:

  ps aux | grep ssh

and check it is listening on port 22:

 netstat -plant | grep :22

more details here

How to get the name of a class without the package?

The following function will work in JDK version 1.5 and above.

public String getSimpleName()

Multithreading in Bash

Sure, just add & after the command:

read_cfg cfgA &
read_cfg cfgB &
read_cfg cfgC &
wait

all those jobs will then run in the background simultaneously. The optional wait command will then wait for all the jobs to finish.

Each command will run in a separate process, so it's technically not "multithreading", but I believe it solves your problem.

Assign a variable inside a Block to a variable outside a Block

Try __weak if you get any warning regarding retain cycle else use __block

Person *strongPerson = [Person new];
__weak Person *weakPerson = person;

Now you can refer weakPerson object inside block.

Split long commands in multiple lines through Windows batch file

You can break up long lines with the caret ^ as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)

Example:

copy file1.txt file2.txt

would be written as:

copy file1.txt^
 file2.txt

update columns values with column of another table based on condition

This will surely work:

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE table2.id=table1.id AND table2.item=table1.item);

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

Using os.walk() to recursively traverse directories in Python

#!/usr/bin/python

import os 

def tracing(a):
    global i>
    for item in os.listdir(a):
        if os.path.isfile(item):
            print i + item 
        else:
            print i + item 
            i+=i
            tracing(item)

i = "---"
tracing(".")

Basic example of using .ajax() with JSONP?

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");

 });
});</script>
</body>
</html> 

The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

Accept server's self-signed ssl certificate in Java client

This is not a solution to the complete problem but oracle has good detailed documentation on how to use this keytool. This explains how to

  1. use keytool.
  2. generate certs/self signed certs using keytool.
  3. import generated certs to java clients.

https://docs.oracle.com/cd/E54932_01/doc.705/e54936/cssg_create_ssl_cert.htm#CSVSG178

Programmatically getting the MAC of an Android device

Getting the MAC address through WifiInfo.getMacAddress() won't work on Marshmallow and above, it has been disabled and will return the constant value of 02:00:00:00:00:00.

LaTeX: remove blank page after a \part or \chapter

It leaves blank pages so that a new part or chapter start on the right-hand side. You can fix this with the "openany" option for the document class. ;)

Parsing arguments to a Java command line program

I like this one. Simple, and you can have more than one parameter for each argument:

final Map<String, List<String>> params = new HashMap<>();

List<String> options = null;
for (int i = 0; i < args.length; i++) {
    final String a = args[i];

    if (a.charAt(0) == '-') {
        if (a.length() < 2) {
            System.err.println("Error at argument " + a);
            return;
        }

        options = new ArrayList<>();
        params.put(a.substring(1), options);
    }
    else if (options != null) {
        options.add(a);
    }
    else {
        System.err.println("Illegal parameter usage");
        return;
    }
}

For example:

-arg1 1 2 --arg2 3 4

System.out.print(params.get("arg1").get(0)); // 1
System.out.print(params.get("arg1").get(1)); // 2
System.out.print(params.get("-arg2").get(0)); // 3
System.out.print(params.get("-arg2").get(1)); // 4

how to create a logfile in php?

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d')) as filename. And now you should know where to start... :)

Swing/Java: How to use the getText and setText string properly

the getText method returns a String, while the setText receives a String, so you can write it like label1.setText(nameField.getText()); in your listener.

Is there a "goto" statement in bash?

Although others have already clarified that there is no direct goto equivalent in bash (and provided the closest alternatives such as functions, loops, and break), I would like to illustrate how using a loop plus break can simulate a specific type of goto statement.

The situation where I find this the most useful is when I need to return to the beginning of a section of code if certain conditions are not met. In the example below, the while loop will run forever until ping stops dropping packets to a test IP.

#!/bin/bash

TestIP="8.8.8.8"

# Loop forever (until break is issued)
while true; do

    # Do a simple test for Internet connectivity
    PacketLoss=$(ping "$TestIP" -c 2 | grep -Eo "[0-9]+% packet loss" | grep -Eo "^[0-9]")

    # Exit the loop if ping is no longer dropping packets
    if [ "$PacketLoss" == 0 ]; then
        echo "Connection restored"
        break
    else
        echo "No connectivity"
    fi
done

Subtract a value from every number in a list in Python?

This will work:

for i in range(len(a)):
  a[i] -= 13

How can I delete an item from an array in VB.NET?

If the array is a string array you are able to then do the following:

AlphaSplit = "a\b\c".Split("\")
MaxIndex   = AlphaSplit.GetUpperBound(0)
AlphaSplit = AlphaSplit.Where(Function(item, index) index <> MaxIndex).ToArray
AlphaJoin  = String.Join("\", PublishRouteSplit)

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Swift version:

import AVFoundation

func playVideo(url: URL) {

    let player = AVPlayer(url: url)

    let layer: AVPlayerLayer = AVPlayerLayer(player: player)
    layer.backgroundColor = UIColor.white.cgColor
    layer.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
    layer.videoGravity = .resizeAspectFill
    self.view.layer.addSublayer(layer)

    player.play()
}

Is object empty?

here my solution

function isEmpty(value) {
    if(Object.prototype.toString.call(value) === '[object Array]') {
        return value.length == 0;
    } else if(value != null && typeof value === 'object') {
        return Object.getOwnPropertyNames(value).length  == 0;
    } else {
        return !(value || (value === 0));
    }
}

Chears

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

To extend one of the answers, also subarrays of multidimensional arrays are passed by value unless passed explicitely by reference.

<?php
$foo = array( array(1,2,3), 22, 33);

function hello($fooarg) {
  $fooarg[0][0] = 99;
}

function world(&$fooarg) {
  $fooarg[0][0] = 66;
}

hello($foo);
var_dump($foo); // (original array not modified) array passed-by-value

world($foo);
var_dump($foo); // (original array modified) array passed-by-reference

The result is:

array(3) {
  [0]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  [1]=>
  int(22)
  [2]=>
  int(33)
}
array(3) {
  [0]=>
  array(3) {
    [0]=>
    int(66)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  [1]=>
  int(22)
  [2]=>
  int(33)
}

Simplest way to detect keypresses in javascript

Don't over complicate.

  document.addEventListener('keydown', logKey);
    function logKey(e) {
      if (`${e.code}` == "ArrowRight") {
        //code here
      }
          if (`${e.code}` == "ArrowLeft") {
        //code here
      }
          if (`${e.code}` == "ArrowDown") {
        //code here
      }
          if (`${e.code}` == "ArrowUp") {
        //code here
      }
    }

Show two digits after decimal point in c++

It is possible to print a 15 decimal number in C++ using the following:

#include <iomanip>
#include <iostream>

cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl;
cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl;
cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl;
cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl;
_getch();

return 0;

Getting multiple keys of specified value of a generic Dictionary?

As everyone else has said, there's no mapping within a dictionary from value to key.

I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.

The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:

using System;
using System.Collections.Generic;

class BiDictionary<TFirst, TSecond>
{
    IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
    IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();

    public void Add(TFirst first, TSecond second)
    {
        if (firstToSecond.ContainsKey(first) ||
            secondToFirst.ContainsKey(second))
        {
            throw new ArgumentException("Duplicate first or second");
        }
        firstToSecond.Add(first, second);
        secondToFirst.Add(second, first);
    }

    public bool TryGetByFirst(TFirst first, out TSecond second)
    {
        return firstToSecond.TryGetValue(first, out second);
    }

    public bool TryGetBySecond(TSecond second, out TFirst first)
    {
        return secondToFirst.TryGetValue(second, out first);
    }
}

class Test
{
    static void Main()
    {
        BiDictionary<int, string> greek = new BiDictionary<int, string>();
        greek.Add(1, "Alpha");
        greek.Add(2, "Beta");
        int x;
        greek.TryGetBySecond("Beta", out x);
        Console.WriteLine(x);
    }
}

How to select all columns, except one column in pandas?

You can drop columns in index:

df[df.columns.drop('b')]

Output:

          a         c         d
0  0.418762  0.869203  0.972314
1  0.991058  0.594784  0.534366
2  0.407472  0.396664  0.894202
3  0.726168  0.324932  0.906575

Change One Cell's Data in mysql

try this.

UPDATE `database_name`.`table_name` SET `column_name`='value' WHERE `id`='1';

How do I set an ASP.NET Label text from code behind on page load?

In your ASP.NET page:

<asp:Label ID="UserNameLabel" runat="server" />

In your code behind (assuming you're using C#):

function Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
       UserNameLabel.Text = "User Name";
    }
}

Windows command for file size only

C:\>FORFILES  /C "cmd /c echo @fname @fsize"


C:\>FORFILES  /?

FORFILES [/P pathname] [/M searchmask] [/S]
         [/C command] [/D [+ | -] {MM/dd/yyyy | dd}]

Description:
    Selects a file (or set of files) and executes a
    command on that file. This is helpful for batch jobs.

Parameter List:
    /P    pathname      Indicates the path to start searching.
                        The default folder is the current working
                        directory (.).

Calling functions in a DLL from C++

Might be useful: https://www.codeproject.com/Articles/6299/Step-by-Step-Calling-C-DLLs-from-VC-and-VB-Part-4

For the example above with "GetWelcomeMessage" you might need to specify "__stdcall" in the typedef field before the function name if getting error after calling imported function.

How to Sort Date in descending order From Arraylist Date in android?

Easier alternative to above answers

  1. If Object(Model Class/POJO) contains the date in String datatype.

    private void sortArray(ArrayList<myObject> arraylist) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
    if (reports != null) {
        Collections.sort(arraylist, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                try {
                    return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
                } catch (ParseException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }
    
  2. If Object(Model Class/POJO) contains date in Date datatype

    private void sortArray(ArrayList<myObject> arrayList) {
    if (arrayList != null) {
        Collections.sort(arrayList, new Comparator<myObject>() {
            @Override
            public int compare(myObject o1, myObject o2) {
                return o2.getCreated_at().compareTo(o1.getCreated_at()); }
        });
    } }
    

The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.

Enumerations on PHP

If you need to use enums that are globally unique (i.e. even when comparing elements between different Enums) and are easy to use, feel free to use the following code. I also added some methods that I find useful. You will find examples in the comments at the very top of the code.

<?php

/**
 * Class Enum
 * 
 * @author Christopher Fox <[email protected]>
 *
 * @version 1.0
 *
 * This class provides the function of an enumeration.
 * The values of Enum elements are unique (even between different Enums)
 * as you would expect them to be.
 *
 * Constructing a new Enum:
 * ========================
 *
 * In the following example we construct an enum called "UserState"
 * with the elements "inactive", "active", "banned" and "deleted".
 * 
 * <code>
 * Enum::Create('UserState', 'inactive', 'active', 'banned', 'deleted');
 * </code>
 *
 * Using Enums:
 * ============
 *
 * The following example demonstrates how to compare two Enum elements
 *
 * <code>
 * var_dump(UserState::inactive == UserState::banned); // result: false
 * var_dump(UserState::active == UserState::active); // result: true
 * </code>
 *
 * Special Enum methods:
 * =====================
 *
 * Get the number of elements in an Enum:
 *
 * <code>
 * echo UserState::CountEntries(); // result: 4
 * </code>
 *
 * Get a list with all elements of the Enum:
 *
 * <code>
 * $allUserStates = UserState::GetEntries();
 * </code>
 *
 * Get a name of an element:
 *
 * <code>
 * echo UserState::GetName(UserState::deleted); // result: deleted
 * </code>
 *
 * Get an integer ID for an element (e.g. to store as a value in a database table):
 * This is simply the index of the element (beginning with 1).
 * Note that this ID is only unique for this Enum but now between different Enums.
 *
 * <code>
 * echo UserState::GetDatabaseID(UserState::active); // result: 2
 * </code>
 */
class Enum
{

    /**
     * @var Enum $instance The only instance of Enum (Singleton)
     */
    private static $instance;

    /**
     * @var array $enums    An array of all enums with Enum names as keys
     *          and arrays of element names as values
     */
    private $enums;

    /**
     * Constructs (the only) Enum instance
     */
    private function __construct()
    {
        $this->enums = array();
    }

    /**
     * Constructs a new enum
     *
     * @param string $name The class name for the enum
     * @param mixed $_ A list of strings to use as names for enum entries
     */
    public static function Create($name, $_)
    {
        // Create (the only) Enum instance if this hasn't happened yet
        if (self::$instance===null)
        {
            self::$instance = new Enum();
        }

        // Fetch the arguments of the function
        $args = func_get_args();
        // Exclude the "name" argument from the array of function arguments,
        // so only the enum element names remain in the array
        array_shift($args);
        self::$instance->add($name, $args);
    }

    /**
     * Creates an enumeration if this hasn't happened yet
     * 
     * @param string $name The class name for the enum
     * @param array $fields The names of the enum elements
     */
    private function add($name, $fields)
    {
        if (!array_key_exists($name, $this->enums))
        {
            $this->enums[$name] = array();

            // Generate the code of the class for this enumeration
            $classDeclaration =     "class " . $name . " {\n"
                        . "private static \$name = '" . $name . "';\n"
                        . $this->getClassConstants($name, $fields)
                        . $this->getFunctionGetEntries($name)
                        . $this->getFunctionCountEntries($name)
                        . $this->getFunctionGetDatabaseID()
                        . $this->getFunctionGetName()
                        . "}";

            // Create the class for this enumeration
            eval($classDeclaration);
        }
    }

    /**
     * Returns the code of the class constants
     * for an enumeration. These are the representations
     * of the elements.
     * 
     * @param string $name The class name for the enum
     * @param array $fields The names of the enum elements
     *
     * @return string The code of the class constants
     */
    private function getClassConstants($name, $fields)
    {
        $constants = '';

        foreach ($fields as $field)
        {
            // Create a unique ID for the Enum element
            // This ID is unique because class and variables
            // names can't contain a semicolon. Therefore we
            // can use the semicolon as a separator here.
            $uniqueID = $name . ";" . $field;
            $constants .=   "const " . $field . " = '". $uniqueID . "';\n";
            // Store the unique ID
            array_push($this->enums[$name], $uniqueID);
        }

        return $constants;
    }

    /**
     * Returns the code of the function "GetEntries()"
     * for an enumeration
     * 
     * @param string $name The class name for the enum
     *
     * @return string The code of the function "GetEntries()"
     */
    private function getFunctionGetEntries($name) 
    {
        $entryList = '';        

        // Put the unique element IDs in single quotes and
        // separate them with commas
        foreach ($this->enums[$name] as $key => $entry)
        {
            if ($key > 0) $entryList .= ',';
            $entryList .= "'" . $entry . "'";
        }

        return  "public static function GetEntries() { \n"
            . " return array(" . $entryList . ");\n"
            . "}\n";
    }

    /**
     * Returns the code of the function "CountEntries()"
     * for an enumeration
     * 
     * @param string $name The class name for the enum
     *
     * @return string The code of the function "CountEntries()"
     */
    private function getFunctionCountEntries($name) 
    {
        // This function will simply return a constant number (e.g. return 5;)
        return  "public static function CountEntries() { \n"
            . " return " . count($this->enums[$name]) . ";\n"
            . "}\n";
    }

    /**
     * Returns the code of the function "GetDatabaseID()"
     * for an enumeration
     * 
     * @return string The code of the function "GetDatabaseID()"
     */
    private function getFunctionGetDatabaseID()
    {
        // Check for the index of this element inside of the array
        // of elements and add +1
        return  "public static function GetDatabaseID(\$entry) { \n"
            . "\$key = array_search(\$entry, self::GetEntries());\n"
            . " return \$key + 1;\n"
            . "}\n";
    }

    /**
     * Returns the code of the function "GetName()"
     * for an enumeration
     *
     * @return string The code of the function "GetName()"
     */
    private function getFunctionGetName()
    {
        // Remove the class name from the unique ID 
        // and return this value (which is the element name)
        return  "public static function GetName(\$entry) { \n"
            . "return substr(\$entry, strlen(self::\$name) + 1 , strlen(\$entry));\n"
            . "}\n";
    }

}


?>

How can I get the current array index in a foreach loop?

You can get the index value with this

foreach ($arr as $key => $val)
{
    $key = (int) $key;
    //With the variable $key you can get access to the current array index
    //You can use $val[$key] to

}

Passing an array to a query using a WHERE clause

As Flavius Stef's answer, you can use intval() to make sure all id are int values:

$ids = join(',', array_map('intval', $galleries));  
$sql = "SELECT * FROM galleries WHERE id IN ($ids)";

What is username and password when starting Spring Boot with Tomcat?

Try to take username and password from below code snipet in your project and login and hope this will work.

@Override
    @Bean
    public UserDetailsService userDetailsService() {
        List<UserDetails> users= new ArrayList<UserDetails>();
        users.add(User.withDefaultPasswordEncoder().username("admin").password("admin").roles("USER","ADMIN").build());
        users.add(User.withDefaultPasswordEncoder().username("spring").password("spring").roles("USER").build());
        return new UserDetailsManager(users);
    }

Remove all whitespace from C# string with regex

Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.

                       new string
                           (stringToRemoveWhiteSpaces
                                .Where
                                (
                                    c => !char.IsWhiteSpace(c)
                                )
                                .ToArray<char>()
                           )

OR

                       new string
                           (stringToReplaceWhiteSpacesWithSpace
                                .Select
                                (
                                    c => char.IsWhiteSpace(c) ? ' ' : c
                                )
                                .ToArray<char>()
                           )

Angular 2.0 and Modal Dialog

Angular 7 + NgBootstrap

A simple way of opening modal from main component and passing result back to it. is what I wanted. I created a step-by-step tutorial which includes creating a new project from scratch, installing ngbootstrap and creation of Modal. You can either clone it or follow the guide.

Hope this helps new to Angular.!

https://github.com/wkaczurba/modal-demo

Details:

modal-simple template (modal-simple.component.html):

<ng-template #content let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">Are you sure?</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <p>You have not finished reading my code. Are you sure you want to close?</p>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="modal.close('yes')">Yes</button>
    <button type="button" class="btn btn-outline-dark" (click)="modal.close('no')">No</button>
  </div>
</ng-template>

The modal-simple.component.ts:

import { Component, OnInit, ViewChild, Output, EventEmitter } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-modal-simple',
  templateUrl: './modal-simple.component.html',
  styleUrls: ['./modal-simple.component.css']
})
export class ModalSimpleComponent implements OnInit {
  @ViewChild('content') content;
  @Output() result : EventEmitter<string> = new EventEmitter();

  constructor(private modalService : NgbModal) { }

  open() {
    this.modalService.open(this.content, {ariaLabelledBy: 'modal-simple-title'})
      .result.then((result) => { console.log(result as string); this.result.emit(result) }, 
        (reason) => { console.log(reason as string); this.result.emit(reason) })
  }

  ngOnInit() {
  }

}

Demo of it (app.component.html) - simple way of dealing with return event:

<app-modal-simple #mymodal (result)="onModalClose($event)"></app-modal-simple>
<button (click)="mymodal.open()">Open modal</button>

<p>
Result is {{ modalCloseResult }}
</p>

app.component.ts - onModalClosed is executed once modal is closed:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  modalCloseResult : string;
  title = 'modal-demo';

  onModalClose(reason : string) {
    this.modalCloseResult = reason;
  }    
}

Cheers

How do I add target="_blank" to a link within a specified div?

I use this for every external link:

window.onload = function(){
  var anchors = document.getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    if (anchors[i].hostname != window.location.hostname) {
        anchors[i].setAttribute('target', '_blank');
    }
  }
}

Better way to check if a Path is a File or a Directory?

I see, I'm 10 years too late to the party. I was facing the situation, where from some property I can receive either a file name or a full file path. If there is no path provided, I have to check the file-existence by attaching a "global" directory-path provided by another property.

In my case

var isFileName = System.IO.Path.GetFileName (str) == str;

did the trick. Ok, it's not magic, but perhaps this could save someone a few minutes of figuring out. Since this is merely a string-parsing, so Dir-names with dots may give false positives...

Dynamically fill in form values with jQuery

If you need to hit the database, you need to hit the web server again (for the most part).

What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.

AJAX calls can be made in jquery with the $.ajax() function call, so this will happen

User's browser enters input that fires a trigger that makes an AJAX call

$('input .callAjax').bind('change', function() { 
  $.ajax({ url: 'script/ajax', 
           type: json
           data: $foo,  
           success: function(data) {
             $('input .targetAjax').val(data.newValue);
           });
  );

Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.

You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.

The php function json_encode($phpobj); will be useful.

A simple scenario using wait() and notify() in java

Have you taken a look at this Java Tutorial?

Further, I'd advise you to stay the heck away from playing with this kind of stuff in real software. It's good to play with it so you know what it is, but concurrency has pitfalls all over the place. It's better to use higher level abstractions and synchronized collections or JMS queues if you are building software for other people.

That is at least what I do. I'm not a concurrency expert so I stay away from handling threads by hand wherever possible.

Formula to determine brightness of RGB color

I have made comparison of the three algorithms in the accepted answer. I generated colors in cycle where only about every 400th color was used. Each color is represented by 2x2 pixels, colors are sorted from darkest to lightest (left to right, top to bottom).

1st picture - Luminance (relative)

0.2126 * R + 0.7152 * G + 0.0722 * B

2nd picture - http://www.w3.org/TR/AERT#color-contrast

0.299 * R + 0.587 * G + 0.114 * B

3rd picture - HSP Color Model

sqrt(0.299 * R^2 + 0.587 * G^2 + 0.114 * B^2)

4th picture - WCAG 2.0 SC 1.4.3 relative luminance and contrast ratio formula (see @Synchro's answer here)

Pattern can be sometimes spotted on 1st and 2nd picture depending on the number of colors in one row. I never spotted any pattern on picture from 3rd or 4th algorithm.

If i had to choose i would go with algorithm number 3 since its much easier to implement and its about 33% faster than the 4th.

Perceived brightness algorithm comparison

Java 8 Distinct by property

You can use the distinct(HashingStrategy) method in Eclipse Collections.

List<Person> persons = ...;
MutableList<Person> distinct =
    ListIterate.distinct(persons, HashingStrategies.fromFunction(Person::getName));

If you can refactor persons to implement an Eclipse Collections interface, you can call the method directly on the list.

MutableList<Person> persons = ...;
MutableList<Person> distinct =
    persons.distinct(HashingStrategies.fromFunction(Person::getName));

HashingStrategy is simply a strategy interface that allows you to define custom implementations of equals and hashcode.

public interface HashingStrategy<E>
{
    int computeHashCode(E object);
    boolean equals(E object1, E object2);
}

Note: I am a committer for Eclipse Collections.

Git push results in "Authentication Failed"

I was adding to Bitbucket linked with Git and had to remove the stored keys, as this was causing the fatal error.

To resolve, I opened the command prompt and ran

 rundll32.exe keymgr.dll, KRShowKeyMgr

I removed the key that was responsible for signing in and next time I pushed the files to the repo, I was prompted for credentials and entered the correct ones, resulting in a successful push.

Iterator over HashMap in Java

Map<String, Car> carMap = new HashMap<String, Car>(16, (float) 0.75);

// there is no iterator for Maps, but there are methods to do this.

        Set<String> keys = carMap.keySet(); // returns a set containing all the keys
        for(String c : keys)
        {

            System.out.println(c);
        }

        Collection<Car> values = carMap.values(); // returns a Collection with all the objects
        for(Car c : values)
        {
            System.out.println(c.getDiscription());
        }
        /*keySet and the values methods serve as “views” into the Map.
          The elements in the set and collection are merely references to the entries in the map, 
          so any changes made to the elements in the set or collection are reflected in the map, and vice versa.*/

        //////////////////////////////////////////////////////////
        /*The entrySet method returns a Set of Map.Entry objects. 
          Entry is an inner interface in the Map interface.
          Two of the methods specified by Map.Entry are getKey and getValue.
          The getKey method returns the key and getValue returns the value.*/

        Set<Map.Entry<String, Car>> cars = carMap.entrySet(); 
        for(Map.Entry<String, Car> e : cars)
        {
            System.out.println("Keys = " + e.getKey());
            System.out.println("Values = " + e.getValue().getDiscription() + "\n");

        }

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

Some social tools like Google+ use a simple method to get a favicon for external links, fetching http://your.domainname.com/favicon.ico

Since they don't prefetch the HTML content, the <link> tag will not work. In this case, you might want to use a mod_rewrite rule or just place the file in the default location.

Entity Framework - Code First - Can't Store List<String>

You can use this ScalarCollection container that confines an array and provides some manipulation options (Gist):

Usage:

public class Person
{
    public int Id { get; set; }
    //will be stored in database as single string.
    public SaclarStringCollection Phones { get; set; } = new ScalarStringCollection();
}

Code:

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace System.Collections.Specialized
{
#if NET462
  [ComplexType]
#endif
  public abstract class ScalarCollectionBase<T> :
#if NET462
    Collection<T>,
#else
    ObservableCollection<T>
#endif
  {
    public virtual string Separator { get; } = "\n";
    public virtual string ReplacementChar { get; } = " ";
    public ScalarCollectionBase(params T[] values)
    {
      if (values != null)
        foreach (var item in Items)
          Items.Add(item);
    }

#if NET462
    [Browsable(false)]
#endif
    [EditorBrowsable(EditorBrowsableState.Never)]
    [Obsolete("Not to be used directly by user, use Items property instead.")]
    public string Data
    {
      get
      {
        var data = Items.Select(item => Serialize(item)
          .Replace(Separator, ReplacementChar.ToString()));
        return string.Join(Separator, data.Where(s => s?.Length > 0));
      }
      set
      {
        Items.Clear();
        if (string.IsNullOrWhiteSpace(value))
          return;

        foreach (var item in value
            .Split(new[] { Separator }, 
              StringSplitOptions.RemoveEmptyEntries).Select(item => Deserialize(item)))
          Items.Add(item);
      }
    }

    public void AddRange(params T[] items)
    {
      if (items != null)
        foreach (var item in items)
          Add(item);
    }

    protected abstract string Serialize(T item);
    protected abstract T Deserialize(string item);
  }

  public class ScalarStringCollection : ScalarCollectionBase<string>
  {
    protected override string Deserialize(string item) => item;
    protected override string Serialize(string item) => item;
  }

  public class ScalarCollection<T> : ScalarCollectionBase<T>
    where T : IConvertible
  {
    protected override T Deserialize(string item) =>
      (T)Convert.ChangeType(item, typeof(T));
    protected override string Serialize(T item) => Convert.ToString(item);
  }
}

How to hide "Showing 1 of N Entries" with the dataTables.js library

try this for hide

$('#table_id').DataTable({
  "info": false
});

and try this for change label

$('#table_id').DataTable({
 "oLanguage": {
               "sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
            },

});

net::ERR_INSECURE_RESPONSE in Chrome

Maybe you have run into this problem: net::ERR_INSECURE_RESPONSE

You need to check the encryption algorithms supported by your server. For example for apache you can configure the cipher suite this way: cipher suite.

Which version of chrome are you running and what is the server serving your APIs?

Deserialize JSON to ArrayList<POJO> using Jackson

You can deserialize directly to a list by using the TypeReference wrapper. An example method:

public static <T> T fromJSON(final TypeReference<T> type,
      final String jsonPacket) {
   T data = null;

   try {
      data = new ObjectMapper().readValue(jsonPacket, type);
   } catch (Exception e) {
      // Handle the problem
   }
   return data;
}

And is used thus:

final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);

TypeReference Javadoc

Fastest way to determine if record exists

Nothing can beat -

SELECT TOP 1 1 FROM products WHERE id = 'some value';

You don't need to count to know if there is a data in table. And don't use alias when not necessary.

How do I see which checkbox is checked?

Try this

index.html

<form action="form.php" method="post">
    Do you like stackoverflow?
    <input type="checkbox" name="like" value="Yes" />  
    <input type="submit" name="formSubmit" value="Submit" /> 
</form>

form.php

<html>
<head>
</head>
<body>

<?php
    if(isset($_POST['like']))
    {
        echo "<h1>You like Stackoverflow.<h1>";
    }
    else
    {
        echo "<h1>You don't like Stackoverflow.</h1>";
    }   
?>

</body>
</html>

Or this

<?php
    if(isset($_POST['like'])) && 
    $_POST['like'] == 'Yes') 
    {
        echo "You like Stackoverflow.";
    }
    else
    {
        echo "You don't like Stackoverflow.";
    }   
?>

Dropdownlist width in IE

check this out.. it's not perfect but it works and it's for IE only and doesn't affect FF. I used the regular javascript for onmousedown to establish IE only fix.. but the msie from jquery could be used as well in the onmousedown.. the main idea is the "onchange" and on blur to have the select box return to normal... decide you're own width for those. I needed 35%.

onmousedown="javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.width='auto'}" 
onchange="this.style.width='35%'"
onblur="this.style.width='35%'"

Provide static IP to docker containers via docker-compose

Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.5

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.6
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1

git ahead/behind info between master and branch?

After doing a git fetch, you can run git status to show how many commits the local branch is ahead or behind of the remote version of the branch.

This won't show you how many commits it is ahead or behind of a different branch though. Your options are the full diff, looking at github, or using a solution like Vimhsa linked above: Git status over all repo's

How to load property file from classpath?

If you use the static method and load the properties file from the classpath folder so you can use the below code :

//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));

Resource files not found from JUnit test cases

Make 'maven.test.skip' as false in pom file, while building project test reource will come under test-classes.

<maven.test.skip>false</maven.test.skip>

How do I iterate through table rows and cells in JavaScript?

If you want one with a functional style, like this:

    const table = document.getElementById("mytab1");
    const cells = table.rows.toArray()
                  .flatMap(row => row.cells.toArray())
                  .map(cell => cell.innerHTML); //["col1 Val1", "col2 Val2", "col1 Val3", "col2 Val4"]

You may modify the prototype object of HTMLCollection (allowing to use in a way that resembles extension methods in C#) and embed into it a function that converts collection into array, allowing to use higher order funcions with the above style (kind of linq style in C#):

    Object.defineProperty(HTMLCollection.prototype, "toArray", {
        value: function toArray() {
            return Array.prototype.slice.call(this, 0);
        },
        writable: true,
        configurable: true
    });

OpenSSL Command to check if a server is presenting a certificate

15841:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:188:
...
SSL handshake has read 0 bytes and written 121 bytes

This is a handshake failure. The other side closes the connection without sending any data ("read 0 bytes"). It might be, that the other side does not speak SSL at all. But I've seen similar errors on broken SSL implementation, which do not understand newer SSL version. Try if you get a SSL connection by adding -ssl3 to the command line of s_client.

Node.js get file extension

It's a lot more efficient to use the substr() method instead of split() & pop()

Have a look at the performance differences here: http://jsperf.com/remove-first-character-from-string

// returns: 'html'
var path = require('path');
path.extname('index.html').substr(1);

enter image description here

Update August 2019 As pointed out by @xentek in the comments; substr() is now considered a legacy function (MDN documentation). You can use substring() instead. The difference between substr() and substring() is that the second argument of substr() is the maximum length to return while the second argument of substring() is the index to stop at (without including that character). Also, substr() accepts negative start positions to be used as an offset from the end of the string while substring() does not.

C++ correct way to return pointer to array from function

Your code is OK. Note though that if you return a pointer to an array, and that array goes out of scope, you should not use that pointer anymore. Example:

int* test (void)
{
    int out[5];
    return out;
}

The above will never work, because out does not exist anymore when test() returns. The returned pointer must not be used anymore. If you do use it, you will be reading/writing to memory you shouldn't.

In your original code, the arr array goes out of scope when main() returns. Obviously that's no problem, since returning from main() also means that your program is terminating.

If you want something that will stick around and cannot go out of scope, you should allocate it with new:

int* test (void)
{
    int* out = new int[5];
    return out;
}

The returned pointer will always be valid. Remember do delete it again when you're done with it though, using delete[]:

int* array = test();
// ...
// Done with the array.
delete[] array;

Deleting it is the only way to reclaim the memory it uses.

Bootstrap onClick button event

If, like me, you had dynamically created buttons on your page, the

$("#your-bs-button's-id").on("click", function(event) {
                       or
$(".your-bs-button's-class").on("click", function(event) {

methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.

$(document).on("click", "#your-bs-button's-id", function(event) {
                       or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {

There are many other references to this issue on stack overflow here and here.

Executing an EXE file using a PowerShell script

& "C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode

or

[System.Diagnostics.Process]::Start("C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe", "C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode")

UPDATE: sorry I missed "(I invoked the command using the "&" operator)" sentence. I had this problem when I was evaluating the path dynamically. Try Invoke-Expression construction:

Invoke-Expression "& `"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe`" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode"

Index of duplicates items in a python list

I made a benchmark of all solutions suggested here and also added another solution to this problem (described in the end of the answer).

Benchmarks

First, the benchmarks. I initialize a list of n random ints within a range [1, n/2] and then call timeit over all algorithms

The solutions of @Paul McGuire and @Ignacio Vazquez-Abrams works about twice as fast as the rest on the list of 100 ints:

Testing algorithm on the list of 100 items using 10000 loops
Algorithm: dupl_eat
Timing: 1.46247477189
####################
Algorithm: dupl_utdemir
Timing: 2.93324529055
####################
Algorithm: dupl_lthaulow
Timing: 3.89198786645
####################
Algorithm: dupl_pmcguire
Timing: 0.583058259784
####################
Algorithm: dupl_ivazques_abrams
Timing: 0.645062989076
####################
Algorithm: dupl_rbespal
Timing: 1.06523873786
####################

If you change the number of items to 1000, the difference becomes much bigger (BTW, I'll be happy if someone could explain why) :

Testing algorithm on the list of 1000 items using 1000 loops
Algorithm: dupl_eat
Timing: 5.46171654555
####################
Algorithm: dupl_utdemir
Timing: 25.5582547323
####################
Algorithm: dupl_lthaulow
Timing: 39.284285326
####################
Algorithm: dupl_pmcguire
Timing: 0.56558489513
####################
Algorithm: dupl_ivazques_abrams
Timing: 0.615980005148
####################
Algorithm: dupl_rbespal
Timing: 1.21610942322
####################

On the bigger lists, the solution of @Paul McGuire continues to be the most efficient and my algorithm begins having problems.

Testing algorithm on the list of 1000000 items using 1 loops
Algorithm: dupl_pmcguire
Timing: 1.5019953958
####################
Algorithm: dupl_ivazques_abrams
Timing: 1.70856155898
####################
Algorithm: dupl_rbespal
Timing: 3.95820421595
####################

The full code of the benchmark is here

Another algorithm

Here is my solution to the same problem:

def dupl_rbespal(c):
    alreadyAdded = False
    dupl_c = dict()
    sorted_ind_c = sorted(range(len(c)), key=lambda x: c[x]) # sort incoming list but save the indexes of sorted items

    for i in xrange(len(c) - 1): # loop over indexes of sorted items
        if c[sorted_ind_c[i]] == c[sorted_ind_c[i+1]]: # if two consecutive indexes point to the same value, add it to the duplicates
            if not alreadyAdded:
                dupl_c[c[sorted_ind_c[i]]] = [sorted_ind_c[i], sorted_ind_c[i+1]]
                alreadyAdded = True
            else:
                dupl_c[c[sorted_ind_c[i]]].append( sorted_ind_c[i+1] )
        else:
            alreadyAdded = False
    return dupl_c

Although it's not the best it allowed me to generate a little bit different structure needed for my problem (i needed something like a linked list of indexes of the same value)

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

Write applications in C or C++ for Android?

Google has already launched Google I/O 2011: Bringing C and C++ Games to Android session which is available at http://www.youtube.com/watch?v=5yorhsSPFG4

which is good to understand the use of NDK for writing application in c and c++ for android.

If you just want to cross compile any console based native game and run them on android then this Article has shown 3 methods for the same.

1: Static compilation using standalone toolchain

2: Cross compilation using Android NDK’s toolchain

3: Cross compilation using AOSP source code

How can I create a copy of an Oracle table without copying the data?

  1. create table xyz_new as select * from xyz;

-- This will create table and copy all data.

  1. delete from xyz_new;

-- This will have same table structure but all data copied will be deleted.

If you want to overcome the limitations specified by answer: How can I create a copy of an Oracle table without copying the data?

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

Default keystore file does not exist?

For Mac/Linux debug keystore, the Android docs have:

keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

But there is something that may not be obvious: If you put the backslash, make sure to do a shift + return in terminal after the backslash so that the second that starts with -alias is on a new line. Simply pasting as-is will not work.

Your terminal (if successful) will look something like this:

$ keytool -exportcert -list -v \
? -alias androiddebugkey -keystore ~/.android/debug.keystore
Enter keystore password: 

The default debug password is: android

Side note: In Android Studio you can manage signing in:

File > Project Structure > Modules - (Your App) > Signing

@Nullable annotation usage

This annotation is commonly used to eliminate NullPointerExceptions. @Nullable says that this parameter might be null. A good example of such behaviour can be found in Google Guice. In this lightweight dependency injection framework you can tell that this dependency might be null. If you would try to pass null without an annotation the framework would refuse to do it's job.

What is more @Nullable might be used with @NotNull annotation. Here you can find some tips on how to use them properly. Code inspection in IntelliJ checks the annotations and helps to debug the code.

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

PHP code to remove everything but numbers

Try this:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

In macOS / Linux (Ubuntu):

1. To Authenticate you need to add your public part of your SSH key pair to bitbucket from within your user settings: User Settings --> SSH keys

You will find the said public part in your ~/.ssh directory, usually id_rsa.pub . note the .pub part of the file name for Public. it will help you to generate one if you don't already have one

You are not done yet ...

2. You need to let your system know what key to use with which remote host, so add these lines to your ~/.ssh/config file

Host bitbucket.org
 IdentityFile ~/.ssh/PRIVATE_KEY_FILE_NAME

Where PRIVATE_KEY_FILE_NAME is the name of private part of your SSH key pair, if you haven't messed with it, usually its default name is : id_rsa in this case replace PRIVATE_KEY_FILE_NAME above with id_rsa(the private key DOES NOT have a .pub extension)

How to make the first option of <select> selected with jQuery

Another way to reset the values (for multiple selected elements) could be this:

$("selector").each(function(){

    /*Perform any check and validation if needed for each item */

    /*Use "this" to handle the element in javascript or "$(this)" to handle the element with jquery */

    this.selectedIndex=0;

});

list all files in the folder and also sub folders

Using you current code, make this tweak:

public void listf(String directoryName, List<File> files) {
    File directory = new File(directoryName);

    // Get all files from a directory.
    File[] fList = directory.listFiles();
    if(fList != null)
        for (File file : fList) {      
            if (file.isFile()) {
                files.add(file);
            } else if (file.isDirectory()) {
                listf(file.getAbsolutePath(), files);
            }
        }
    }
}

How to generate unique id in MySQL?

You may like the way that we do it. I wanted a reversible unique code that looked "random" -a fairly common problem.

  • We take an input number such as 1,942.
  • Left pad it into a string: "0000001942"
  • Put the last two digits onto the front: "4200000019"
  • Convert that into a number: 4,200,000,019

We now have a number that varies wildly between calls and is guaranteed to be less than 10,000,000,000. Not a bad start.

  • Convert that number to a Base 34 string: "2oevc0b"
  • Replace any zeros with 'y' and any ones with 'z': "2oevcyb"
  • Upshift: "2OEVCYB"

The reason for choosing base 34 is so that we don't worry about 0/O and 1/l collisions. Now you have a short random-looking key that you can use to look up a LONG database identifier.

Convert utf8-characters to iso-88591 and back in PHP

First of all, don't use different encodings. It leads to a mess, and UTF-8 is definitely the one you should be using everywhere.

Chances are your input is not ISO-8859-1, but something else (ISO-8859-15, Windows-1252). To convert from those, use iconv or mb_convert_encoding.

Nevertheless, utf8_encode and utf8_decode should work for ISO-8859-1. It would be nice if you could post a link to a file or a uuencoded or base64 example string for which the conversion fails or yields unexpected results.

How can I find the number of arguments of a Python function?

inspect.getargspec()

Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.

Changed in version 2.6: Returns a named tuple ArgSpec(args, varargs, keywords, defaults).

See can-you-list-the-keyword-arguments-a-python-function-receives.

Remove lines that contain certain string

to_skip = ("bad", "naughty")
out_handle = open("testout", "w")

with open("testin", "r") as handle:
    for line in handle:
        if set(line.split(" ")).intersection(to_skip):
            continue
        out_handle.write(line)
out_handle.close()

How to read the output from git diff?

On my mac:

info diff then select: Output formats -> Context -> Unified format -> Detailed Unified :

Or online man diff on gnu following the same path to the same section:

File: diff.info, Node: Detailed Unified, Next: Example Unified, Up: Unified Format

Detailed Description of Unified Format ......................................

The unified output format starts with a two-line header, which looks like this:

 --- FROM-FILE FROM-FILE-MODIFICATION-TIME
 +++ TO-FILE TO-FILE-MODIFICATION-TIME

The time stamp looks like `2002-02-21 23:30:39.942229878 -0800' to indicate the date, time with fractional seconds, and time zone.

You can change the header's content with the `--label=LABEL' option; see *Note Alternate Names::.

Next come one or more hunks of differences; each hunk shows one area where the files differ. Unified format hunks look like this:

 @@ FROM-FILE-RANGE TO-FILE-RANGE @@
  LINE-FROM-EITHER-FILE
  LINE-FROM-EITHER-FILE...

The lines common to both files begin with a space character. The lines that actually differ between the two files have one of the following indicator characters in the left print column:

`+' A line was added here to the first file.

`-' A line was removed here from the first file.

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Just perform the following steps:

1a) Connect to mysql (via localhost)

mysql -uroot -p

1b) If the mysql server is running in Kubernetes (K8s) and being accessed via a NodePort

kubectl exec -it [pod-name] -- /bin/bash
mysql -uroot -p
  1. Create user

    CREATE USER 'user'@'%' IDENTIFIED BY 'password';

  2. Grant permissions

    GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' WITH GRANT OPTION;

  3. Flush privileges

    FLUSH PRIVILEGES;

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

Mockito: Inject real objects into private @Autowired fields

I know this is an old question, but we were faced with the same problem when trying to inject Strings. So we invented a JUnit5/Mockito extension that does exactly what you want: https://github.com/exabrial/mockito-object-injection

EDIT:

@InjectionMap
 private Map<String, Object> injectionMap = new HashMap<>();

 @BeforeEach
 public void beforeEach() throws Exception {
  injectionMap.put("securityEnabled", Boolean.TRUE);
 }

 @AfterEach
 public void afterEach() throws Exception {
  injectionMap.clear();
 }

How do you get the footer to stay at the bottom of a Web page?

Use CSS vh units!

Probably the most obvious and non-hacky way to go about a sticky footer would be to make use of the new css viewport units.

Take for example the following simple markup:

<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>

If the header is say 80px high and the footer is 40px high, then we can make our sticky footer with one single rule on the content div:

.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
}

Which means: let the height of the content div be at least 100% of the viewport height minus the combined heights of the header and footer.

That's it.

_x000D_
_x000D_
* {_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
header {_x000D_
    background: yellow;_x000D_
    height: 80px;_x000D_
}_x000D_
.content {_x000D_
    min-height: calc(100vh - 120px);_x000D_
    /* 80px header + 40px footer = 120px  */_x000D_
    background: pink;_x000D_
}_x000D_
footer {_x000D_
    height: 40px;_x000D_
    background: aqua;_x000D_
}
_x000D_
<header>header goes here</header>_x000D_
<div class="content">This page has little content</div>_x000D_
<footer>This is my footer</footer>
_x000D_
_x000D_
_x000D_

... and here's how the same code works with lots of content in the content div:

_x000D_
_x000D_
* {_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
header {_x000D_
    background: yellow;_x000D_
    height: 80px;_x000D_
}_x000D_
.content {_x000D_
    min-height: calc(100vh - 120px);_x000D_
    /* 80px header + 40px footer = 120px  */_x000D_
    background: pink;_x000D_
}_x000D_
footer {_x000D_
    height: 40px;_x000D_
    background: aqua;_x000D_
}
_x000D_
<header>header goes here</header>_x000D_
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum._x000D_
</div>_x000D_
<footer>_x000D_
    This is my footer_x000D_
</footer>
_x000D_
_x000D_
_x000D_

NB:

1) The height of the header and footer must be known

2) Old versions of IE (IE8-) and Android (4.4-) don't support viewport units. (caniuse)

3) Once upon a time webkit had a problem with viewport units within a calc rule. This has indeed been fixed (see here) so there's no problem there. However if you're looking to avoid using calc for some reason you can get around that using negative margins and padding with box-sizing -

Like so:

_x000D_
_x000D_
* {_x000D_
    margin:0;padding:0;_x000D_
}_x000D_
header {_x000D_
    background: yellow;_x000D_
    height: 80px;_x000D_
    position:relative;_x000D_
}_x000D_
.content {_x000D_
    min-height: 100vh;_x000D_
    background: pink;_x000D_
    margin: -80px 0 -40px;_x000D_
    padding: 80px 0 40px;_x000D_
    box-sizing:border-box;_x000D_
}_x000D_
footer {_x000D_
    height: 40px;_x000D_
    background: aqua;_x000D_
}
_x000D_
<header>header goes here</header>_x000D_
<div class="content">Lorem ipsum _x000D_
</div>_x000D_
<footer>_x000D_
    This is my footer_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Angular.js: How does $eval work and why is it different from vanilla eval?

From the test,

it('should allow passing locals to the expression', inject(function($rootScope) {
  expect($rootScope.$eval('a+1', {a: 2})).toBe(3);

  $rootScope.$eval(function(scope, locals) {
    scope.c = locals.b + 4;
  }, {b: 3});
  expect($rootScope.c).toBe(7);
}));

We also can pass locals for evaluation expression.

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

i found another solution:

  1. start session in TEAM
  2. go to SOURCE CONTROL and select WORKSPACE (mark in red)
  3. then Add new Workspace... why?
  4. because you dont work in the same workspace whey you change your account in TFS (i dont know why)
  5. and ready to MAP your project again.

Its 100% guaranteed to work.

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

What does Docker add to lxc-tools (the userspace LXC tools)?

Let's take a look at the list of Docker's technical features, and check which ones are provided by LXC and which ones aren't.

Features:

1) Filesystem isolation: each process container runs in a completely separate root filesystem.

Provided with plain LXC.

2) Resource isolation: system resources like cpu and memory can be allocated differently to each process container, using cgroups.

Provided with plain LXC.

3) Network isolation: each process container runs in its own network namespace, with a virtual interface and IP address of its own.

Provided with plain LXC.

4) Copy-on-write: root filesystems are created using copy-on-write, which makes deployment extremely fast, memory-cheap and disk-cheap.

This is provided by AUFS, a union filesystem that Docker depends on. You could set up AUFS yourself manually with LXC, but Docker uses it as a standard.

5) Logging: the standard streams (stdout/stderr/stdin) of each process container is collected and logged for real-time or batch retrieval.

Docker provides this.

6) Change management: changes to a container's filesystem can be committed into a new image and re-used to create more containers. No templating or manual configuration required.

"Templating or manual configuration" is a reference to LXC, where you would need to learn about both of these things. Docker allows you to treat containers in the way that you're used to treating virtual machines, without learning about LXC configuration.

7) Interactive shell: docker can allocate a pseudo-tty and attach to the standard input of any container, for example to run a throwaway interactive shell.

LXC already provides this.


I only just started learning about LXC and Docker, so I'd welcome any corrections or better answers.

Using iFrames In ASP.NET

try this

<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>

Expose this iframe in the master page's codebehind:

public HtmlControl iframe
{
get
{
return this.myIframe;
}
}

Add the MasterType directive for the content page to strongly typed Master Page.

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>

In code behind

protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}

How to unpack pkl file?

The pickle (and gzip if the file is compressed) module need to be used

NOTE: These are already in the standard Python library. No need to install anything new

SQLite UPSERT / UPDATE OR INSERT

This is a late answer. Starting from SQLIte 3.24.0, released on June 4, 2018, there is finally a support for UPSERT clause following PostgreSQL syntax.

INSERT INTO players (user_name, age)
  VALUES('steven', 32) 
  ON CONFLICT(user_name) 
  DO UPDATE SET age=excluded.age;

Note: For those having to use a version of SQLite earlier than 3.24.0, please reference this answer below (posted by me, @MarqueIV).

However if you do have the option to upgrade, you are strongly encouraged to do so as unlike my solution, the one posted here achieves the desired behavior in a single statement. Plus you get all the other features, improvements and bug fixes that usually come with a more recent release.

Angular2 router (@angular/router), how to set default route?

The path should be left blank to make it default component.

{ path: '', component: DashboardComponent },

Spin or rotate an image on hover

It's very simple.

  1. You add an image.
  2. You create a css property to this image.

    img { transition: all 0.3s ease-in-out 0s; }
    
  3. You add an animation like that:

    img:hover
    {
        cursor: default;
        transform: rotate(360deg);
        transition: all 0.3s ease-in-out 0s;
    }
    

Why do I get the "Unhandled exception type IOException"?

I got the Error even though i was catching the exception.

    try {
        bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
    } catch (IOException e) {
        Log.e("blabla", "Error", e);
        finish();
    }

Issue was that the IOException wasn't imported

import java.io.IOException;

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Insert data into hive table

You can insert new data into table by two ways.

  1. Load the data of a file into table using load command.

    LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename.
    
  2. You can insert new data into table by using select query.

    INSERT INTO table tablename1 select columnlist FROM secondtable;
    

What is external linkage and internal linkage?

Basically

  • extern linkage variable is visible in all files
  • internal linkage variable is visible in single file.

Explain: const variables internally link by default unless otherwise declared as extern

  1. by default, global variable is external linkage
  2. but, const global variable is internal linkage
  3. extra, extern const global variable is external linkage

A pretty good material about linkage in C++

http://www.goldsborough.me/c/c++/linker/2016/03/30/19-34-25-internal_and_external_linkage_in_c++/

Java - Change int to ascii

If you first convert the int to a char, you will have your ascii code.

For example:

    int iAsciiValue = 9; // Currently just the number 9, but we want Tab character
    // Put the tab character into a string
    String strAsciiTab = Character.toString((char) iAsciiValue);

extract date only from given timestamp in oracle sql

This is exactly what TO_DATE() is for: to convert timestamp to date.

Just use TO_DATE(sysdate) instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS').

SQLFiddle demo

UPDATE:

Per your update, your cdate column is not real DATE or TIMESTAMP type, but VARCHAR2. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.

You should convert your cdate VARCHAR2 field into real TIMESTAMP. Assuming there are no other users for this field except for your code, you can convert cdate to timestamp as follows:

BEGIN TRANSACTION;
-- add new temp field tdate:
ALTER TABLE mytable ADD tdate TIMESTAMP;
-- save cdate to tdate while converting it:
UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');

-- you may want to check contents of tdate before next step!!!

-- drop old field
ALTER TABLE mytable DROP COLUMN cdate;
-- rename tdate to cdate:
ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
COMMIT;

SQLFiddle Demo

CSS3 transitions inside jQuery .css()

Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.

Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.

JS Fiddle Live Demo

Javascript:

$("#startTransition").on("click", function()
{

    if( $(".boxOne").is(":visible")) 
    {
        $(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
        $(".boxTwo").css({ x: '100%' });
        $(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
        return;        
    }

    $(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
    $(".boxOne").css({ x: '100%' });
    $(".boxOne").show().transition({ x: '0%', opacity: 1.0 });

});

Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

.append(), prepend(), .after() and .before()

The best way is going to documentation.

.append() vs .after()

  • .append(): Insert content, specified by the parameter, to the end of each element in the set of matched elements.
  • .after(): Insert content, specified by the parameter, after each element in the set of matched elements.

.prepend() vs .before()

  • prepend(): Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
  • .before(): Insert content, specified by the parameter, before each element in the set of matched elements.

So, append and prepend refers to child of the object whereas after and before refers to sibling of the the object.

Increment counter with loop

Try the following:

<c:set var="count" value="0" scope="page" />

//in your loops
<c:set var="count" value="${count + 1}" scope="page"/>

Is it possible to overwrite a function in PHP

Monkey patch in namespace php >= 5.3

A less evasive method than modifying the interpreter is the monkey patch.

Monkey patching is the art of replacing the actual implementation with a similar "patch" of your own.

Ninja skills

Before you can monkey patch like a PHP Ninja we first have to understand PHPs namespaces.

Since PHP 5.3 we got introduced to namespaces which you might at first glance denote to be equivalent to something like java packages perhaps, but it's not quite the same. Namespaces, in PHP, is a way to encapsulate scope by creating a hierarchy of focus, especially for functions and constants. As this topic, fallback to global functions, aims to explain.

If you don't provide a namespace when calling a function, PHP first looks in the current namespace then moves down the hierarchy until it finds the first function declared within that prefixed namespace and executes that. For our example if you are calling print_r(); from namespace My\Awesome\Namespace; What PHP does is to first look for a function called My\Awesome\Namespace\print_r(); then My\Awesome\print_r(); then My\print_r(); until it finds the PHP built in function in the global namespace \print_r();.

You will not be able to define a function print_r($object) {} in the global namespace because this will cause a name collision since a function with that name already exists.

Expect a fatal error to the likes of:

Fatal error: Cannot redeclare print_r()

But nothing stops you, however, from doing just that within the scope of a namespace.

Patching the monkey

Say you have a script using several print_r(); calls.

Example:

<?php
     print_r($some_object);
     // do some stuff
     print_r($another_object);
     // do some other stuff
     print_r($data_object);
     // do more stuff
     print_r($debug_object);

But you later change your mind and you want the output wrapped in <pre></pre> tags instead. Ever happened to you?

Before you go and change every call to print_r(); consider monkey patching instead.

Example:

<?php
    namespace MyNamespace {
        function print_r($object) 
        {
            echo "<pre>", \print_r($object, true), "</pre>"; 
        }

        print_r($some_object);
        // do some stuff
        print_r($another_object);
        // do some other stuff
        print_r($data_object);
        // do more stuff
        print_r($debug_object);
    }

Your script will now be using MyNamespace\print_r(); instead of the global \print_r();

Works great for mocking unit tests.

nJoy!

How to tell if UIViewController's view is visible

if you're utilizing a UINavigationController and also want to handle modal views, the following is what i use:

#import <objc/runtime.h>

UIViewController* topMostController = self.navigationController.visibleViewController;
if([[NSString stringWithFormat:@"%s", class_getName([topMostController class])] isEqualToString:@"NAME_OF_CONTROLLER_YOURE_CHECKING_IN"]) {
    //is topmost visible view controller
}

PL/SQL, how to escape single quote in a string?

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

Build an iOS app without owning a mac?

Let me tell you step by step few years back I was in same situation.

So We have two Phases

  1. iPhone/iPad (iOS) app development
  2. iPhone/iPad (iOS) app development and Publish to iTunes Store

1. iPhone/iPad (iOS) app development

So If you just want to develop iOS apps you don't want to pay anything,

You just need Mac + XCode IDE

  1. Get Mac Mini or Mac Machine
  2. Create Developer Account on Apple its free
  3. After login developer account you can download Xcode IDE's .dmg file
  4. That's all.

Now you just install Xcode and start developing iOS apps and test/debug with Simulator..

2. iPhone/iPad (iOS) app development and Publish to iTunes Store

for publishing your app on iTunes store you need to pay (example $99 / year) .

So For complete iOS Development Setup you need

  1. Get Mac Mini or Mac Machine
  2. Create Developer Account on Apple its free
  3. After login developer account you can download Xcode IDE's .dmg file
  4. pay $99 for publish apps on iTunes
  5. create your certificates for development/distribution on your apple account
  6. download all certificate on mac machine and install into XCode using Keychain tool
  7. Get at least one iOS Device
  8. Register you device on your apple account
  9. Now you can develop iOS app, test on Real Device and also publish on iTunes Store

Matrix multiplication using arrays

Try this,

public static Double[][] multiplicar(Double A[][],Double B[][]){
    Double[][] C= new Double[2][2];
    int i,j,k;
     for (i = 0; i < 2; i++) {
         for (j = 0; j < 2; j++) {
             C[i][j] = 0.00000;
         }
     }
    for(i=0;i<2;i++){
        for(j=0;j<2;j++){
            for (k=0;k<2;k++){
                  C[i][j]+=(A[i][k]*B[k][j]);

            }

        }
    }
    return C;
}

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

This is usually caused by your CSV having been saved along with an (unnamed) index (RangeIndex).

(The fix would actually need to be done when saving the DataFrame, but this isn't always an option.)

Workaround: read_csv with index_col=[0] argument

IMO, the simplest solution would be to read the unnamed column as the index. Specify an index_col=[0] argument to pd.read_csv, this reads in the first column as the index. (Note the square brackets).

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

# Save DataFrame to CSV.
df.to_csv('file.csv')

<!- ->

pd.read_csv('file.csv')

   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

# Now try this again, with the extra argument.
pd.read_csv('file.csv', index_col=[0])

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

Note
You could have avoided this in the first place by using index=False if the output CSV was created in pandas, if your DataFrame does not have an index to begin with:

df.to_csv('file.csv', index=False)

But as mentioned above, this isn't always an option.


Stopgap Solution: Filtering with str.match

If you cannot modify the code to read/write the CSV file, you can just remove the column by filtering with str.match:

df 

   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

df.columns
# Index(['Unnamed: 0', 'a', 'b', 'c'], dtype='object')

df.columns.str.match('Unnamed')
# array([ True, False, False, False])

df.loc[:, ~df.columns.str.match('Unnamed')]
 
   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

How To Auto-Format / Indent XML/HTML in Notepad++

Just install the latest notepad++ and install indent By fold. On the menu bar select Plugins -> Plugins Admin and selct indent By fold and the install. Works finest

C++ templates that accept only certain types

class Base
{
    struct FooSecurity{};
};

template<class Type>
class Foo
{
    typename Type::FooSecurity If_You_Are_Reading_This_You_Tried_To_Create_An_Instance_Of_Foo_For_An_Invalid_Type;
};

Make sure derived classes inherit the FooSecurity structure and the compiler will get upset in all the right places.

How to check for an active Internet connection on iOS or macOS?

Important: This check should always be performed asynchronously. The majority of answers below are synchronous so be careful otherwise you'll freeze up your app.


Swift

1) Install via CocoaPods or Carthage: https://github.com/ashleymills/Reachability.swift

2) Test reachability via closures

let reachability = Reachability()!

reachability.whenReachable = { reachability in
    if reachability.connection == .wifi {
        print("Reachable via WiFi")
    } else {
        print("Reachable via Cellular")
    }
}

reachability.whenUnreachable = { _ in
    print("Not reachable")
}

do {
    try reachability.startNotifier()
} catch {
    print("Unable to start notifier")
}

Objective-C

1) Add SystemConfiguration framework to the project but don't worry about including it anywhere

2) Add Tony Million's version of Reachability.h and Reachability.m to the project (found here: https://github.com/tonymillion/Reachability)

3) Update the interface section

#import "Reachability.h"

// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
    Reachability *internetReachableFoo;
}
@end

4) Then implement this method in the .m file of your view controller which you can call

// Checks if we have an internet connection or not
- (void)testInternetConnection
{   
    internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];

    // Internet is reachable
    internetReachableFoo.reachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Yayyy, we have the interwebs!");
        });
    };

    // Internet is not reachable
    internetReachableFoo.unreachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Someone broke the internet :(");
        });
    };

    [internetReachableFoo startNotifier];
}

Important Note: The Reachability class is one of the most used classes in projects so you might run into naming conflicts with other projects. If this happens, you'll have to rename one of the pairs of Reachability.h and Reachability.m files to something else to resolve the issue.

Note: The domain you use doesn't matter. It's just testing for a gateway to any domain.

Get index of array element faster than O(n)

Taking a combination of @sawa's answer and the comment listed there you could implement a "quick" index and rindex on the array class.

class Array
  def quick_index el
    hash = Hash[self.map.with_index.to_a]
    hash[el]
  end

  def quick_rindex el
    hash = Hash[self.reverse.map.with_index.to_a]
    array.length - 1 - hash[el]
  end
end

How to convert integers to characters in C?

In C, int, char, long, etc. are all integers.

They typically have different memory sizes and thus different ranges as in INT_MIN to INT_MAX. char and arrays of char are often used to store characters and strings. Integers are stored in many types: int being the most popular for a balance of speed, size and range.

ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.

int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;

To convert an int to a char, simple assign:

int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4; 

This warning comes up because int typically has a greater range than char and so some loss-of-information may occur. By using the cast (char), the potential loss of info is explicitly directed.

To print the value of an integer:

printf("<%c>\n", c3); // prints <b>

// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>

// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>

printf("<%d>\n", i3); // prints <98>

There are additional issues about printing such as using %hhu or casting when printing an unsigned char, but leave that for later. There is a lot to printf().

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This configuration to your nginx.conf should help you.

https://gist.github.com/baskaran-md/e46cc25ccfac83f153bb

server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    error_page  404     /404.html;
    error_page  403     /403.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    # ...
}

Spring - @Transactional - What happens in background?

When Spring loads your bean definitions, and has been configured to look for @Transactional annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).

However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with @Transactional, Spring will create a TransactionInterceptor, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the TransactionInterceptor (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the TransactionInterceptor commits/rolls back the transaction. It's transparent to the client code.

As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.

Does that help?

Manually install Gradle and use it in Android Studio

Like @ said

https://services.gradle.org/distributions/

Download The Latest Gradle Distribution File and Extract It, Then Copy all Files and Paste it Under:

C:\Users\{USERNAME}\.gradle\wrapper\dists\

but you have to first make Android Studio try downloading the zip file and cancel it.

That way you can get the hash and copy the file and put it under the hash

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I had various JDK from 1.5 to 1.7 installed on my PC. I had a need to learn JDK1.8 so installed and my earlier versions of Eclipse (depended on earlier versions of JDK) and I got errors launching my Eclipse IDE, on the command line I tried to check the Java Version and got the error below,

C:\>java -version
Registry key 'Software\JavaSoft\Java Runtime Environment\CurrentVersion'
has value '1.8', but '1.6' is required.
Error: could not find java.dll
Error: could not find Java SE Runtime Environment.

Solution:- I removed

C:\ProgramData\Oracle\Java\javapath;
from the PATH variable and moved %JAVA%\bin to the start of the PATH variable, that solved the problem for me.

Iterating over Typescript Map

If you don't really like nested functions, you can also iterate over the keys:

myMap : Map<string, boolean>;
for(let key of myMap) {
   if (myMap.hasOwnProperty(key)) {
       console.log(JSON.stringify({key: key, value: myMap[key]}));
   }
}

Note, you have to filter out the non-key iterations with the hasOwnProperty, if you don't do this, you get a warning or an error.

What is the most efficient way of finding all the factors of a number in Python?

from functools import reduce

def factors(n):    
    return set(reduce(list.__add__, 
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

This will return all of the factors, very quickly, of a number n.

Why square root as the upper limit?

sqrt(x) * sqrt(x) = x. So if the two factors are the same, they're both the square root. If you make one factor bigger, you have to make the other factor smaller. This means that one of the two will always be less than or equal to sqrt(x), so you only have to search up to that point to find one of the two matching factors. You can then use x / fac1 to get fac2.

The reduce(list.__add__, ...) is taking the little lists of [fac1, fac2] and joining them together in one long list.

The [i, n/i] for i in range(1, int(sqrt(n)) + 1) if n % i == 0 returns a pair of factors if the remainder when you divide n by the smaller one is zero (it doesn't need to check the larger one too; it just gets that by dividing n by the smaller one.)

The set(...) on the outside is getting rid of duplicates, which only happens for perfect squares. For n = 4, this will return 2 twice, so set gets rid of one of them.

Which browsers support <script async="async" />?

A comprehensive list of browser versions supporting the async parameter is available here

Where is localhost folder located in Mac or Mac OS X?

If you use apachectl to start or stop, then you can find it with this command

apachectl -t -D DUMP_RUN_CFG

Warn user before leaving web page with unsaved changes

Universal solution requiring no configuration that automatically detects all input modification, including contenteditable elements:

"use strict";
(() => {
const modified_inputs = new Set;
const defaultValue = "defaultValue";
// store default values
addEventListener("beforeinput", (evt) => {
    const target = evt.target;
    if (!(defaultValue in target || defaultValue in target.dataset)) {
        target.dataset[defaultValue] = ("" + (target.value || target.textContent)).trim();
    }
});
// detect input modifications
addEventListener("input", (evt) => {
    const target = evt.target;
    let original;
    if (defaultValue in target) {
        original = target[defaultValue];
    } else {
        original = target.dataset[defaultValue];
    }
    if (original !== ("" + (target.value || target.textContent)).trim()) {
        if (!modified_inputs.has(target)) {
            modified_inputs.add(target);
        }
    } else if (modified_inputs.has(target)) {
        modified_inputs.delete(target);
    }
});
// clear modified inputs upon form submission
addEventListener("submit", () => {
    modified_inputs.clear();
    // to prevent the warning from happening, it is advisable
    // that you clear your form controls back to their default
    // state with form.reset() after submission
});
// warn before closing if any inputs are modified
addEventListener("beforeunload", (evt) => {
    if (modified_inputs.size) {
        const unsaved_changes_warning = "Changes you made may not be saved.";
        evt.returnValue = unsaved_changes_warning;
        return unsaved_changes_warning;
    }
});
})();

What is the difference between Release and Debug modes in Visual Studio?

Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.

As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.

List of all users that can connect via SSH

Any user with a valid shell in /etc/passwd can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.

To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

For windows you can do it like

"scripts": {
    "start:prod" : "SET NODE_ENV=production & nodemon app.js",
    "start:dev" : "SET NODE_ENV=development & nodemon app.js"
},

Hidden features of Python

Slices & Mutability

Copying lists

>>> x = [1,2,3]
>>> y = x[:]
>>> y.pop()
3
>>> y
[1, 2]
>>> x
[1, 2, 3]

Replacing lists

>>> x = [1,2,3]
>>> y = x
>>> y[:] = [4,5,6]
>>> x
[4, 5, 6]

How to create a number picker dialog?

Consider using a Spinner instead of a Number Picker in a Dialog. It's not exactly what was asked for, but it's much easier to implement, more contextual UI design, and should fulfill most use cases. The equivalent code for a Spinner is:

Spinner picker = new Spinner(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, yourStringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
picker.setAdapter(adapter);

Request Permission for Camera and Library in iOS 10 - Info.plist

Swift 5 The easiest way to add permissions without having to do it programatically, is to open your info.plist file and select the + next to Information Property list. Scroll through the drop down list to the Privacy options and select Privacy Camera Usage Description for accessing camera, or Privacy Photo Library Usage Description for accessing the Photo Library. Fill in the String value on the right after you've made your selection, to include the text you would like displayed to your user when the alert pop up asks for permissions. Camera/Photo Library permission

How to compare two floating point numbers in Bash?

I was posting this as an answer to https://stackoverflow.com/a/56415379/1745001 when it got closed as a dup of this question so here it is as it applies here too:

For simplicity and clarity just use awk for the calculations as it's a standard UNIX tool and so just as likely to be present as bc and much easier to work with syntactically.

For this question:

$ cat tst.sh
#!/bin/bash

num1=3.17648e-22
num2=1.5

awk -v num1="$num1" -v num2="$num2" '
BEGIN {
    print "num1", (num1 < num2 ? "<" : ">="), "num2"
}
'

$ ./tst.sh
num1 < num2

and for that other question that was closed as a dup of this one:

$ cat tst.sh
#!/bin/bash

read -p "Operator: " operator
read -p "First number: " ch1
read -p "Second number: " ch2

awk -v ch1="$ch1" -v ch2="$ch2" -v op="$operator" '
BEGIN {
    if ( ( op == "/" ) && ( ch2 == 0 ) ) {
        print "Nope..."
    }
    else {
        print ch1 '"$operator"' ch2
    }
}
'

$ ./tst.sh
Operator: /
First number: 4.5
Second number: 2
2.25

$ ./tst.sh
Operator: /
First number: 4.5
Second number: 0
Nope...

powershell is missing the terminator: "

In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

Sending event when AngularJS finished loading

If you are using Angular UI Router, you can listen for the $viewContentLoadedevent.

"$viewContentLoaded - fired once the view is loaded, after the DOM is rendered. The '$scope' of the view emits the event." - Link

$scope.$on('$viewContentLoaded', 
function(event){ ... });

Using "If cell contains" in VBA excel

This will loop through all cells in a given range that you define ("RANGE TO SEARCH") and add dashes at the cell below using the Offset() method. As a best practice in VBA, you should never use the Select method.

Sub AddDashes()

Dim SrchRng As Range, cel As Range

Set SrchRng = Range("RANGE TO SEARCH")

For Each cel In SrchRng
    If InStr(1, cel.Value, "TOTAL") > 0 Then
        cel.Offset(1, 0).Value = "-"
    End If
Next cel

End Sub

Possible reason for NGINX 499 error codes

Turns out 499's really does mean "client interrupted connection."

I had a client "read timeout" setting of 60s (and nginx also has a default proxy_read_timeout of 60s). So what was happening in my case is that nginx would error.log an upstream timed out (110: Connection timed out) while reading upstream and then nginx retries "the next proxy server in the backend server group you configured." That's if you have more than one.

Then it tries the next and next till (by default) it has exhausted all of them. As each one times out, it removes them from the list of "live" backend servers, as well. After all are exhausted, it returns a 504 gateway timeout.

So in my case nginx marked the server as "unavailable", re-tried it on the next server, then my client's 60s timeout (immediately) occurred, so I'd see a upstream timed out (110: Connection timed out) while reading upstream log, immediately followed by a 499 log. But it was just timing coincidence.

Related:

If all servers in the group are marked as currently unavailable, then it returns a 502 Bad Gateway. for 10s as well. See here max_fails and fail_timeout. Inn the logs it will say no live upstreams while connecting to upstream.

If you only have one proxy backend in your server group, it just try's the one server, and returns a 504 Gateway Time-out and doesn't remove the single server from the list of "live" servers, if proxy_read_timeout is surpassed. See here "If there is only a single server in a group, max_fails, fail_timeout and slow_start parameters are ignored, and such a server will never be considered unavailable."

The really tricky part is that if you specify proxy_pass to "localhost" and your box happens to also have ipv6 and ipv4 "versions of location" on it at the same time (most boxes do by default), it will count as if you had a "list" of multiple servers in your server group, which means you can get into the situation above of having it return "502 for 10s" even though you list only one server. See here "If a domain name resolves to several addresses, all of them will be used in a round-robin fashion." One workaround is to declare it as proxy_pass http://127.0.0.1:5001; (its ipv4 address) to avoid it being both ipv6 and ipv4. Then it counts as "only a single server" behavior.

There's a few different settings you can tweak to make this "less" of a problem. Like increasing timeouts or making it so it doesn't mark servers as "disabled" when they timeout...or fixing the list so it's only size 1, see above :)

See also: https://serverfault.com/a/783624/27813

Using 24 hour time in bootstrap timepicker

"YYYY-MM-DD HH:mm:ss" => 24 hours format;

"YYYY-MM-DD hh:mm:ss" => 12 hours format;

the difference is letter 'H'

MySQL compare DATE string with string from DATETIME field

If you want to select all rows where the DATE part of a DATETIME column matches a certain literal, you cannot do it like so:

WHERE startTime = '2010-04-29'

because MySQL cannot compare a DATE and a DATETIME directly. What MySQL does, it extends the given DATE literal with the time '00:00:00'. So your condition becomes

WHERE startTime = '2010-04-29 00:00:00'

Certainly not what you want!

The condition is a range and hence it should be given as range. There are several possibilities:

WHERE startTime BETWEEN '2010-04-29 00:00:00' AND '2010-04-29 23:59:59'
WHERE startTime >= '2010-04-29' AND startTime < ('2010-04-29' + INTERVAL 1 DAY)

There is a tiny possibility for the first to be wrong - when your DATETIME column uses subsecond resolution and there is an appointment at 23:59:59 + epsilon. In general I suggest to use the second variant.

Both variants can use an index on startTime which will become important when the table grows.

How to include scripts located inside the node_modules folder?

I want to update this question with an easier solution. Create a symbolic link to node_modules.

The easiest way to grant public access to node_modules is to create a symbolic link pointing to your node_modules from within your public directory. The symlink will make it as if the files exist wherever the link is created.

For example, if the node server has code for serving static files

app.use(serveStatic(path.join(__dirname, 'dist')));

and __dirname refers to /path/to/app so that your static files are served from /path/to/app/dist

and node_modules is at /path/to/app/node_modules, then create a symlink like this on mac/linux:

ln -s /path/to/app/node_modules /path/to/app/dist/node_modules

or like this on windows:

mklink /path/to/app/node_modules /path/to/app/dist/node_modules

Now a get request for:

node_modules/some/path 

will receive a response with the file at

/path/to/app/dist/node_modules/some/path 

which is really the file at

/path/to/app/node_modules/some/path

If your directory at /path/to/app/dist is not a safe location, perhaps because of interference from a build process with gulp or grunt, then you could add a separate directory for the link and add a new serveStatic call such as:

ln -s /path/to/app/node_modules /path/to/app/newDirectoryName/node_modules

and in node add:

app.use(serveStatic(path.join(__dirname, 'newDirectoryName')));

How to enable support of CPU virtualization on Macbook Pro?

Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.

How to check that Intel VT-x is supported in CPU:

  1. Open Terminal application from Application/Utilities

  2. Copy/paste command bellow

sysctl -a | grep machdep.cpu.features

  1. You may see output similar to:

Mac:~ user$ sysctl -a | grep machdep.cpu.features kern.exec: unknown type returned machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM

If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.

Refer to this link on Apple.com to enable hardware support for virtualization:

How to execute a JavaScript function when I have its name as a string

Depending on where you are you can also use:

this["funcname"]();
self["funcname"]();
window["funcname"]();
top["funcname"]();
globalThis["funcname"]();

or, in nodejs

global["funcname"]()

Identifying Exception Type in a handler Catch Block

When dealing with situations where I don't exactly know what type of exception might come out of a method, a little "trick" I like to do is to recover the Exception's class name and add it to the error log so there is more information.

try
{
   <code>

} catch ( Exception caughtEx )
{
   throw new Exception("Unknown Exception Thrown: "
                       + "\n  Type:    " + caughtEx.GetType().Name
                       + "\n  Message: " + caughtEx.Message);
}

I do vouch for always handling Exceptions types individually, but the extra bit of info can be helpful, specially when dealing with code from people who love to capture catch-all generic types.

What LaTeX Editor do you suggest for Linux?

Honestly, I've always been happy with emacs. Then again, I started out using emacs, so I've no doubt that it colours my perceptions. Still, it gives syntax highlighting and formatting, and can easily be configured to build the LaTeX. Check out the TeX mode.

Cosine Similarity between 2 Number Lists

All the answers are great for situations where you cannot use NumPy. If you can, here is another approach:

def cosine(x, y):
    dot_products = np.dot(x, y.T)
    norm_products = np.linalg.norm(x) * np.linalg.norm(y)
    return dot_products / (norm_products + EPSILON)

Also bear in mind about EPSILON = 1e-07 to secure the division.

How to find indices of all occurrences of one string in another in JavaScript?

Check this solution which will able to find same character string too, let me know if something missing or not right.

_x000D_
_x000D_
function indexes(source, find) {_x000D_
    if (!source) {_x000D_
      return [];_x000D_
    }_x000D_
    if (!find) {_x000D_
        return source.split('').map(function(_, i) { return i; });_x000D_
    }_x000D_
    source = source.toLowerCase();_x000D_
    find = find.toLowerCase();_x000D_
    var result = [];_x000D_
    var i = 0;_x000D_
    while(i < source.length) {_x000D_
      if (source.substring(i, i + find.length) == find)_x000D_
        result.push(i++);_x000D_
      else_x000D_
        i++_x000D_
    }_x000D_
    return result;_x000D_
  }_x000D_
  console.log(indexes('aaaaaaaa', 'aaaaaa'))_x000D_
  console.log(indexes('aeeaaaaadjfhfnaaaaadjddjaa', 'aaaa'))_x000D_
  console.log(indexes('wordgoodwordgoodgoodbestword', 'wordgood'))_x000D_
  console.log(indexes('I learned to play the Ukulele in Lebanon.', 'le'))
_x000D_
_x000D_
_x000D_

How to use delimiter for csv in python

ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv

with open(r"C:\\test.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["a","b"])

you have to set the delimiter = ","

Determine if char is a num or letter

chars are just integers, so you can actually do a straight comparison of your character against literals:

if( c >= '0' && c <= '9' ){

This applies to all characters. See your ascii table.

ctype.h also provides functions to do this for you.

How to disable or enable viewpager swiping in android

This worked for me.

   ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // disable swipe
            if(!swipeEnabled) {
                if (viewPager.getAdapter().getCount()>1) {
                    viewPager.setCurrentItem(1);
                    viewPager.setCurrentItem(0);
                }
            }
        }
        public void onPageScrollStateChanged(int state) {}
        public void onPageSelected(int position) {}
    };
    viewPager.addOnPageChangeListener(onPageChangeListener);

How to extract the first two characters of a string in shell scripting?

colrm — remove columns from a file

To leave first two chars, just remove columns starting from 3

cat file | colrm 3

How to format DateTime in Flutter , How to get current time in flutter?

You can also use this syntax. For YYYY-MM-JJ HH-MM:

var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';

Push items into mongo array via mongoose

I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.

---- Person model

const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema   = mongoose.Schema;

const productSchema = new Schema({
  friends    : [SingleFriend.schema]
});

module.exports = mongoose.model('Person', personSchema);

***Important: SingleFriend.schema -> make sure to use lowercase for schema

--- Child schema

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const SingleFriendSchema = new Schema({
  Name: String
});

module.exports = mongoose.model('SingleFriend', SingleFriendSchema);

Why do some functions have underscores "__" before and after the function name?

Added an example to understand the use of __ in python. Here is the list of All __

https://docs.python.org/3/genindex-all.html#_

Certain classes of identifiers (besides keywords) have special meanings. Any use of * names, in any other context, that does not follow explicitly documented use, is subject to breakage without warning

Access restriction using __

"""
Identifiers:
-  Contain only (A-z, 0-9, and _ )
-  Start with a lowercase letter or _.
-  Single leading _ :  private
-  Double leading __ :  strong private
-  Start & End  __ : Language defined Special Name of Object/ Method
-  Class names start with an uppercase letter.
-

"""


class BankAccount(object):
    def __init__(self, name, money, password):
        self.name = name            # Public
        self._money = money         # Private : Package Level
        self.__password = password  # Super Private

    def earn_money(self, amount):
        self._money += amount
        print("Salary Received: ", amount, " Updated Balance is: ", self._money)

    def withdraw_money(self, amount):
        self._money -= amount
        print("Money Withdraw: ", amount, " Updated Balance is: ", self._money)

    def show_balance(self):
        print(" Current Balance is: ", self._money)


account = BankAccount("Hitesh", 1000, "PWD")  # Object Initalization

# Method Call
account.earn_money(100)

# Show Balance
print(account.show_balance())

print("PUBLIC ACCESS:", account.name)  # Public Access

# account._money is accessible because it is only hidden by convention
print("PROTECTED ACCESS:", account._money)  # Protected Access

# account.__password will throw error but account._BankAccount__password will not
# because __password is super private
print("PRIVATE ACCESS:", account._BankAccount__password)

# Method Call
account.withdraw_money(200)

# Show Balance
print(account.show_balance())

# account._money is accessible because it is only hidden by convention
print(account._money)  # Protected Access

How to check how many letters are in a string in java?

To answer your questions in a easy way:

    a) String.length();
    b) String.charAt(/* String index */);

How can I make Bootstrap 4 columns all the same height?

Equal height columns is the default behaviour for Bootstrap 4 grids.

_x000D_
_x000D_
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
      <br>_x000D_
      Line 2_x000D_
      <br>_x000D_
      Line 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Bootstrap 3 only for mobile

You can create a jQuery function to unload Bootstrap CSS files at the size of 768px, and load it back when resized to lower width. This way you can design a mobile website without touching the desktop version, by using col-xs-* only

function resize() {
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}   
else {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', false);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', false);
}
}

and

$(document).ready(function() {
$(window).resize(resize);
resize();   

if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}
});

What is <scope> under <dependency> in pom.xml for?

If we don't provide any scope then the default scope is compile, If you want to confirm, simply go to Effective pom tab in eclipse editor, it will show you as compile.

What is a semaphore?

Semaphore can also be used as a ... semaphore. For example if you have multiple process enqueuing data to a queue, and only one task consuming data from the queue. If you don't want your consuming task to constantly poll the queue for available data, you can use semaphore.

Here the semaphore is not used as an exclusion mechanism, but as a signaling mechanism. The consuming task is waiting on the semaphore The producing task are posting on the semaphore.

This way the consuming task is running when and only when there is data to be dequeued

How to provide password to a command that prompts for one in bash?

How to use autoexpect to pipe a password into a command:

These steps are illustrated with an Ubuntu 12.10 desktop. The exact commands for your distribution may be slightly different.

This is dangerous because you risk exposing whatever password you use to anyone who can read the autoexpect script file.

DO NOT expose your root password or power user passwords by piping them through expect like this. Root kits WILL find this in an instant and your box is owned.

EXPECT spawns a process, reads text that comes in then sends text predefined in the script file.

  1. Make sure you have expect and autoexpect installed:

    sudo apt-get install expect
    sudo apt-get install expect-dev
    
  2. Read up on it:

    man expect
    man autoexpect
    
  3. Go to your home directory:

    cd /home/el
    
  4. User el cannot chown a file to root and must enter a password:

    touch testfile.txt
    sudo chown root:root testfile.txt 
       [enter password to authorize the changing of the owner]
    
  5. This is the password entry we want to automate. Restart the terminal to ensure that sudo asks us for the password again. Go to /home/el again and do this:

    touch myfile.txt
    
    autoexpect -f my_test_expect.exp sudo chown root:root myfile.txt
    
        [enter password which authorizes the chown to root]
    
    autoexpect done, file is my_test_expect.exp
    
  6. You have created my_test_expect.exp file. Your super secret password is stored plaintext in this file. This should make you VERY uncomfortable. Mitigate some discomfort by restricting permissions and ownership as much as possible:

    sudo chown el my_test_expect.exp     //make el the owner.
    sudo chmod 700 my_test_expect.exp    //make file only readable by el.
    
  7. You see these sorts of commands at the bottom of my_test_expect.exp:

    set timeout -1
    spawn sudo chown root:root myfile.txt
    match_max 100000
    expect -exact "\[sudo\] password for el: "
    send -- "YourPasswordStoredInPlaintext\r"
    expect eof
    
  8. You will need to verify that the above expect commands are appropriate. If the autoexpect script is being overly sensitive or not sensitive enough then it will hang. In this case it's acceptable because the expect is waiting for text that will always arrive.

  9. Run the expect script as user el:

    expect my_test_expect.exp 
    spawn sudo chown root:root myfile.txt
    [sudo] password for el: 
    
  10. The password contained in my_test_expect.exp was piped into a chown to root by user el. To see if the password was accepted, look at myfile.txt:

    ls -l
    -rw-r--r--  1 root root          0 Dec  2 14:48 myfile.txt
    

It worked because it is root, and el never entered a password. If you expose your root, sudo, or power user password with this script, then acquiring root on your box will be easy. Such is the penalty for a security system that lets everybody in no questions asked.

How do I enable php to work with postgresql?

in my case there are 2 php.ini, I had to uncomment extension pdo_pgsql in both php.ini

  1. in php folder
  2. in apache folder

both inside in wamp folder

Insert an element at a specific index in a list and return the updated list

The shortest I got: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

Binary numbers in Python

Below is a re-write of a previously posted function:

def addBinary(a, b): # Example: a = '11' + b =' 100' returns as '111'.    
    for ch in a: assert ch in {'0','1'}, 'bad digit: ' + ch    
    for ch in b: assert ch in {'0','1'}, 'bad digit: ' + ch    
    sumx = int(a, 2) + int(b, 2)    
    return bin(sumx)[2:]

CSS selector based on element text?

I know it's not exactly what you are looking for, but maybe it'll help you.

You can try use a jQuery selector :contains(), add a class and then do a normal style for a class.

Empty or Null value display in SSRS text boxes

I had a similar situation but the following worked best for me..

=Iif(Fields!Sales_Diff.Value)>1,Fields!Sales_Diff.Value),"")

Redirect website after certain amount of time

<meta http-equiv="refresh" content="3;url=http://www.google.com/" />

How to rebase local branch onto remote master

git fetch origin master:master pulls the latest version of master without needing to check it out.

So all you need is:

git fetch origin master:master && git rebase master

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *. Also, the map method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply is used for.

So, if you must use the above approach, I would write it like this

df["A1"], df["A2"] = zip(*df["a"].apply(calculate))

There's actually no reason to use zip here. You can simply do this:

df["A1"], df["A2"] = calculate(df['a'])

This second method is also much faster on larger DataFrames

df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})

DataFrame created with 300,000 rows

%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

60x faster than zip


In general, avoid using apply

Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above

%%timeit
A1, A2 = [], []
for val in df['a']:
    A1.append(val**2)
    A2.append(val**3)

df['A1'] = A1
df['A2'] = A2

298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:

%load_ext cython

%%cython
cpdef power(vals):
    A1, A2 = [], []
    cdef double val
    for val in vals:
        A1.append(val**2)
        A2.append(val**3)

    return A1, A2

%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Directly assigning without apply

You can get even greater speed improvements if you use the direct vectorized operations.

%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.


The simplest speed test with apply

The above example should clearly show how slow apply can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply

s = pd.Series(np.random.rand(10000000))

%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Without apply is 50x faster

%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Hibernate SessionFactory vs. JPA EntityManagerFactory

EntityManagerFactory is the standard implementation, it is the same across all the implementations. If you migrate your ORM for any other provider like EclipseLink, there will not be any change in the approach for handling the transaction. In contrast, if you use hibernate’s session factory, it is tied to hibernate APIs and cannot migrate to new vendor.

How to get numbers after decimal point?

Sometimes trailing zeros matter

In [4]: def split_float(x):
   ...:     '''split float into parts before and after the decimal'''
   ...:     before, after = str(x).split('.')
   ...:     return int(before), (int(after)*10 if len(after)==1 else int(after))
   ...: 
   ...: 

In [5]: split_float(105.10)
Out[5]: (105, 10)

In [6]: split_float(105.01)
Out[6]: (105, 1)

In [7]: split_float(105.12)
Out[7]: (105, 12)

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

You can do it using the "collapse" directive: http://jsfiddle.net/iscrow/Es4L3/ (check the two "Note" in the HTML).

        <!-- Note: set the initial collapsed state and change it when clicking -->
        <a ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed" class="btn btn-navbar">
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
        </a>
        <a class="brand" href="#">Title</a>
           <!-- Note: use "collapse" here. The original "data-" settings are not needed anymore. -->
           <div collapse="navCollapsed" class="nav-collapse collapse navbar-responsive-collapse">
              <ul class="nav">

That is, you need to store the collapsed state in a variable, and changing the collapsed also by (simply) changing the value of that variable.


Release 0.14 added a uib- prefix to components:

https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes

Change: collapse to uib-collapse.

How to determine day of week by passing specific date?

Calendar cal = Calendar.getInstance(desired date);
cal.setTimeInMillis(System.currentTimeMillis());
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

Get the day value by providing the current time stamp.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

Sort array of objects by object fields

if you're using php oop you might need to change to:

public static function cmp($a, $b) 
{
    return strcmp($a->name, $b->name);
}

//in this case FUNCTION_NAME would be cmp
usort($your_data, array('YOUR_CLASS_NAME','FUNCTION_NAME')); 

Python list iterator behavior and next(iterator)

Something is wrong with your Python/Computer.

a = iter(list(range(10)))
for i in a:
   print(i)
   next(a)

>>> 
0
2
4
6
8

Works like expected.

Tested in Python 2.7 and in Python 3+ . Works properly in both

@AspectJ pointcut for all methods of a class with specific annotation

The simplest way seems to be :

@Around("execution(@MyHandling * com.exemple.YourService.*(..))")
public Object aroundServiceMethodAdvice(final ProceedingJoinPoint pjp)
   throws Throwable {
   // perform actions before

   return pjp.proceed();

   // perform actions after
}

It will intercept execution of all methods specifically annotated with '@MyHandling' in 'YourService' class. To intercept all methods without exception, just put the annotation directly on the class.

No matter of the private / public scope here, but keep in mind that spring-aop cannot use aspect for method calls in same instance (typically private ones), because it doesn't use the proxy class in this case.

We use @Around advice here, but it's basically the same syntax with @Before, @After or any advice.

By the way, @MyHandling annotation must be configured like this :

@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.TYPE })
public @interface MyHandling {

}