Programs & Examples On #Google finance

Google Finance is a service used to track stock and portfolio information. Originally had a public API, but the API is scheduled for shutdown on October 20, 2012.

How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function

The syntax is:

=GOOGLEFINANCE(ticker, [attribute], [start_date], [num_days|end_date], [interval])

Sample usage:

=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
=GOOGLEFINANCE("GOOG","price",TODAY()-30,TODAY())
=GOOGLEFINANCE(A2,A3)
=117.80*Index(GOOGLEFINANCE("CURRENCY:EURGBP", "close", DATE(2014,1,1)), 2, 2)

For instance if you'd like to convert the rate on specific date, here is some more advanced example:

=IF($C2 = "GBP", "", Index(GoogleFinance(CONCATENATE("CURRENCY:", C2, "GBP"), "close", DATE(year($A2), month($A2), day($A2)), DATE(year($A2), month($A2), day($A2)+1), "DAILY"), 2))

where $A2 is your date (e.g. 01/01/2015) and C2 is your currency (e.g. EUR).

See more samples at Docs editors Help at Google.

Alternative to google finance api

I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.

Download all stock symbol list of a market

This may be old, but... if you change the link in google stock list as below:

https://www.google.com/finance?q=%5B(exchange%20%3D%3D%20%22NASDAQ%22)%5D&restype=company&noIL=1&num=30000

  • note for the noIL=1&num=30000

It means, starting for row 1 to 30000. It shows all results in one page.

You may automate it using any language or just export the table to excel.

Hope it helps.

How to make google spreadsheet refresh itself every 1 minute?

GOOGLEFINANCE can have a 20 minutes delay, so refreshing every minute would not really help.

Instead of GOOGLEFINANCE you can use different source. I'm using this RealTime stock prices(I tried a couple but this is the easiest by-far to implement. They have API that retuen JSON { Name: CurrentPrice }

Here's a little script you can use in Google Sheets(Tools->Script Editor)

function GetStocksPrice() {      
   var url = 'https://financialmodelingprep.com/api/v3/stock/real-time- 
   price/AVP,BAC,CHK,CY,GE,GPRO,HIMX,IMGN,MFG,NIO,NMR,SSSS,UCTT,UMC,ZNGA';
   var response = UrlFetchApp.fetch(url);

   // convert json string to json object
   var jsonSignal = JSON.parse(response);    

  // define an array of all the object keys
  var headerRow = Object.keys(jsonSignal);
  // define an array of all the object values
  var values = headerRow.map(function(key){ return jsonSignal[key]});   
  var data = values[0];

  // get sheet by ID -  
  // you can get the sheet unqiue ID from the your current sheet url
  var jsonSheet = SpreadsheetApp.openById("Your Sheet UniqueID");  
  //var name = jsonSheet.getName();

  var sheet = jsonSheet.getSheetByName('Sheet1'); 

  // the column to put the data in -> Y
  var letter = "F";

  // start from line 
  var index = 4;
  data.forEach(function( row, index2 ) { 

     var keys = Object.keys(row);
     var value2 = row[keys[1]];            

     // set value loction
     var cellXY = letter +  index;      
     sheet.getRange(cellXY).setValue(value2);  
  
     index = index + 1;    
 });  
}

Now you need to add a trigger that will execute every minute.

  1. Go to Project Triggers -> click on the Watch icon next to the Save icon
  2. Add Trigger
  3. In -> Choose which function to run -> GetStocksPrice
  4. In -> Select event source -> Time-driven
  5. In -> Select type of time based trigger -> Minutes timer
  6. In -> Select minute interval -> Every minute

And your set :)

Download history stock prices automatically from yahoo finance in python

There is already a library in Python called yahoo_finance so you'll need to download the library first using the following command line:

sudo pip install yahoo_finance

Then once you've installed the yahoo_finance library, here's a sample code that will download the data you need from Yahoo Finance:

#!/usr/bin/python
import yahoo_finance
import pandas as pd

symbol = yahoo_finance.Share("GOOG")
google_data = symbol.get_historical("1999-01-01", "2016-06-30")
google_df = pd.DataFrame(google_data)

# Output data into CSV
google_df.to_csv("/home/username/google_stock_data.csv")

This should do it. Let me know if it works.

UPDATE: The yahoo_finance library is no longer supported.

How can I get stock quotes using Google Finance API?

Edit: the api call has been removed by google. so it is no longer functioning.

Agree with Pareshkumar's answer. Now there is a python wrapper googlefinance for the url call.

Install googlefinance

$pip install googlefinance

It is easy to get current stock price:

>>> from googlefinance import getQuotes
>>> import json
>>> print json.dumps(getQuotes('AAPL'), indent=2)
[
  {
    "Index": "NASDAQ", 
    "LastTradeWithCurrency": "129.09", 
    "LastTradeDateTime": "2015-03-02T16:04:29Z", 
    "LastTradePrice": "129.09", 
    "Yield": "1.46", 
    "LastTradeTime": "4:04PM EST", 
    "LastTradeDateTimeLong": "Mar 2, 4:04PM EST", 
    "Dividend": "0.47", 
    "StockSymbol": "AAPL", 
    "ID": "22144"
  }
]

Google finance is a source that provides real-time stock data. There are also other APIs from yahoo, such as yahoo-finance, but they are delayed by 15min for NYSE and NASDAQ stocks.

How to change line width in IntelliJ (from 120 character)

I didn't understand why my this didn't work but I found out that this setting is now also under the programming language itself at:

'Editor' | 'Code Style' | < your language > | 'Wrapping and Braces' | 'Right margin (columns)'

Plotting of 1-dimensional Gaussian distribution function

With the excellent matplotlib and numpy packages

from matplotlib import pyplot as mp
import numpy as np

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
    mp.plot(x_values, gaussian(x_values, mu, sig))

mp.show()

will produce something like plot showing one-dimensional gaussians produced by matplotlib

php is null or empty?

This is not a bug but PHP normal behavior. It happens because the == operator in PHP doesn't check for type.

'' == null == 0 == false

If you want also to check if the values have the same type, use === instead. To study in deep this difference, please read the official documentation.

Identify duplicate values in a list in Python

You can use list compression and set to reduce the complexity.

my_list = [3, 5, 2, 1, 4, 4, 1]
opt = [item for item in set(my_list) if my_list.count(item) > 1]

How does the keyword "use" work in PHP and can I import classes with it?

The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.

You can check out this article on the autoloading functionality of PHP. There are many implementations of this type of functionality in frameworks already.

I've actually implemented one before. Here's a link.

Passing environment-dependent variables in webpack

To add to the bunch of answers personally I prefer the following:

const webpack = require('webpack');
const prod = process.argv.indexOf('-p') !== -1;

module.exports = {
  ...
  plugins: [
    new webpack.DefinePlugin({
      process: {
        env: {
          NODE_ENV: prod? `"production"`: '"development"'
        }
      }
    }),
    ...
  ]
};

Using this there is no funky env variable or cross-platform problems (with env vars). All you do is run the normal webpack or webpack -p for dev or production respectively.

Reference: Github issue

Get day of week in SQL Server 2005/2008

this is a working copy of my code check it, how to retrive day name from date in sql

CREATE Procedure [dbo].[proc_GetProjectDeploymentTimeSheetData] 
@FromDate date,
@ToDate date

As 
Begin
select p.ProjectName + ' ( ' + st.Time +' '+'-'+' '+et.Time +' )' as ProjectDeatils,
datename(dw,pts.StartDate) as 'Day'
from 
ProjectTimeSheet pts 
join Projects p on pts.ProjectID=p.ID 
join Timing st on pts.StartTimingId=st.Id
join Timing et on pts.EndTimingId=et.Id
where pts.StartDate >= @FromDate
and pts.StartDate <= @ToDate
END

Datatables on-the-fly resizing

This did the trick for me.

$('#dataTable').resize()

What Vim command(s) can be used to quote/unquote words?

surround.vim is going to be your easiest answer. If you are truly set against using it, here are some examples for what you can do. Not necessarily the most efficient, but that's why surround.vim was written.

  • Quote a word, using single quotes
    ciw'Ctrl+r"'
    • ciw - Delete the word the cursor is on, and end up in insert mode.
    • ' - add the first quote.
    • Ctrl+r" - Insert the contents of the " register, aka the last yank/delete.
    • ' - add the closing quote.

  • Unquote a word that's enclosed in single quotes
    di'hPl2x
    • di' - Delete the word enclosed by single quotes.
    • hP - Move the cursor left one place (on top of the opening quote) and put the just deleted text before the quote.
    • l - Move the cursor right one place (on top of the opening quote).
    • 2x - Delete the two quotes.

  • Change single quotes to double quotes
    va':s/\%V'\%V/"/g
    • va' - Visually select the quoted word and the quotes.
    • :s/ - Start a replacement.
    • \%V'\%V - Only match single quotes that are within the visually selected region.
    • /"/g - Replace them all with double quotes.

Grep regex NOT containing string

patterns[1]="1\.2\.3\.4.*Has exploded"
patterns[2]="5\.6\.7\.8.*Has died"
patterns[3]="\!9\.10\.11\.12.*Has exploded"

for i in {1..3}
 do
grep "${patterns[$i]}" logfile.log
done

should be the the same as

egrep "(1\.2\.3\.4.*Has exploded|5\.6\.7\.8.*Has died)" logfile.log | egrep -v "9\.10\.11\.12.*Has exploded"    

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

Change the Bootstrap Modal effect

 body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}

    <div class="container">
    <form class="form-inline" style="position:absolute; top:40%; left:50%; transform:translateX(-50%);">
        <div class="form-group">
        <label>Entrances</label>
          <select class="form-control" id="entrance">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Entrances">
              <option value="bounceIn" selected>bounceIn</option>
              <option value="bounceInDown">bounceInDown</option>
              <option value="bounceInLeft">bounceInLeft</option>
              <option value="bounceInRight">bounceInRight</option>
              <option value="bounceInUp">bounceInUp</option>
            </optgroup>
            <optgroup label="Fading Entrances">
              <option value="fadeIn">fadeIn</option>
              <option value="fadeInDown">fadeInDown</option>
              <option value="fadeInDownBig">fadeInDownBig</option>
              <option value="fadeInLeft">fadeInLeft</option>
              <option value="fadeInLeftBig">fadeInLeftBig</option>
              <option value="fadeInRight">fadeInRight</option>
              <option value="fadeInRightBig">fadeInRightBig</option>
              <option value="fadeInUp">fadeInUp</option>
              <option value="fadeInUpBig">fadeInUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipInX">flipInX</option>
              <option value="flipInY">flipInY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedIn">lightSpeedIn</option>
            </optgroup>
            <optgroup label="Rotating Entrances">
              <option value="rotateIn">rotateIn</option>
              <option value="rotateInDownLeft">rotateInDownLeft</option>
              <option value="rotateInDownRight">rotateInDownRight</option>
              <option value="rotateInUpLeft">rotateInUpLeft</option>
              <option value="rotateInUpRight">rotateInUpRight</option>
            </optgroup>
            <optgroup label="Sliding Entrances">
              <option value="slideInUp">slideInUp</option>
              <option value="slideInDown">slideInDown</option>
              <option value="slideInLeft">slideInLeft</option>
              <option value="slideInRight">slideInRight</option>
            </optgroup>
            <optgroup label="Zoom Entrances">
              <option value="zoomIn">zoomIn</option>
              <option value="zoomInDown">zoomInDown</option>
              <option value="zoomInLeft">zoomInLeft</option>
              <option value="zoomInRight">zoomInRight</option>
              <option value="zoomInUp">zoomInUp</option>
            </optgroup>

            <optgroup label="Specials">
              <option value="rollIn">rollIn</option>
            </optgroup>
          </select>
       </div>
        <div class="form-group">
        <label>Exits</label>
          <select class="form-control" id="exit">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Exits">
              <option value="bounceOut">bounceOut</option>
              <option value="bounceOutDown">bounceOutDown</option>
              <option value="bounceOutLeft">bounceOutLeft</option>
              <option value="bounceOutRight">bounceOutRight</option>
              <option value="bounceOutUp">bounceOutUp</option>
            </optgroup>
            <optgroup label="Fading Exits">
              <option value="fadeOut">fadeOut</option>
              <option value="fadeOutDown">fadeOutDown</option>
              <option value="fadeOutDownBig">fadeOutDownBig</option>
              <option value="fadeOutLeft">fadeOutLeft</option>
              <option value="fadeOutLeftBig">fadeOutLeftBig</option>
              <option value="fadeOutRight">fadeOutRight</option>
              <option value="fadeOutRightBig">fadeOutRightBig</option>
              <option value="fadeOutUp">fadeOutUp</option>
              <option value="fadeOutUpBig">fadeOutUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipOutX" selected>flipOutX</option>
              <option value="flipOutY">flipOutY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedOut">lightSpeedOut</option>
            </optgroup>
            <optgroup label="Rotating Exits">
              <option value="rotateOut">rotateOut</option>
              <option value="rotateOutDownLeft">rotateOutDownLeft</option>
              <option value="rotateOutDownRight">rotateOutDownRight</option>
              <option value="rotateOutUpLeft">rotateOutUpLeft</option>
              <option value="rotateOutUpRight">rotateOutUpRight</option>
            </optgroup>
            <optgroup label="Sliding Exits">
              <option value="slideOutUp">slideOutUp</option>
              <option value="slideOutDown">slideOutDown</option>
              <option value="slideOutLeft">slideOutLeft</option>
              <option value="slideOutRight">slideOutRight</option>
            </optgroup>        
            <optgroup label="Zoom Exits">
              <option value="zoomOut">zoomOut</option>
              <option value="zoomOutDown">zoomOutDown</option>
              <option value="zoomOutLeft">zoomOutLeft</option>
              <option value="zoomOutRight">zoomOutRight</option>
              <option value="zoomOutUp">zoomOutUp</option>
            </optgroup>
            <optgroup label="Specials">
              <option value="rollOut">rollOut</option>
            </optgroup>

          </select>
       </div>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
      Launch demo modal
    </button>
    </form>

      <a class="btn btn-black " href="http://demo.nhembram.com/bootstrap-modal-animation-with-animate-css/index.html" target="_blank">View FullPage</a>
    </div>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>

    <script>
    function testAnim(x) {
        $('.modal .modal-dialog').attr('class', 'modal-dialog  ' + x + '  animated');
    };
    $('#myModal').on('show.bs.modal', function (e) {
      var anim = $('#entrance').val();
          testAnim(anim);
    });
    $('#myModal').on('hide.bs.modal', function (e) {
      var anim = $('#exit').val();
          testAnim(anim);
    });
    </script>

<style>
body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}
</style>

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

Disable PHP in directory (including all sub-directories) with .htaccess

<Directory /your/directorypath/>
     php_admin_value engine Off
</Directory>

DataGridView - Focus a specific cell

I had a similar problem. I've hidden some columns and afterwards I tried to select the first row. This didn't really work:

datagridview1.Rows[0].Selected = true;

So I tried selecting cell[0,0], but it also didn't work, because this cell was not displayed. Now my final solution is working very well:

datagridview1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;    
datagridview1.CurrentCell = datagridview1.FirstDisplayedCell;

So this selects the complete first row.

Change default global installation directory for node.js modules in Windows?

The default global folder is C:\Users\{username}\AppData\Roaming\npm. You can create (if it doesn't exist) a .npmrc file in C:\Users\{username}\ and add prefix = "path\\to\\yourglobalfolder". Note that, in windows, the path should be separated by double back-slash.

How do I remove all non-ASCII characters with regex and Notepad++?

Another way...

  1. Install the Text FX plugin if you don't have it already
  2. Go to the TextFX menu option -> zap all non printable characters to #. It will replace all invalid chars with 3 # symbols
  3. Go to Find/Replace and look for ###. Replace it with a space.

This is nice if you can't remember the regex or don't care to look it up. But the regex mentioned by others is a nice solution as well.

Git pull after forced update

Pull with rebase

A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull command:

git pull --rebase

How to fluently build JSON in Java?

String json = new JsonBuilder(new GsonAdapter())
  .object("key1", "value1")
  .object("key2", "value2")
  .object("key3")
    .object("innerKey1", "value3")
    .build().toString();

If you think the above solution is elegant, then please try out my JsonBuilder lib. It was created to allow one way of building json structures for many types of Json libraries. Current implementations include Gson, Jackson and MongoDB. For ie. Jackson just swap:

String json = new JsonBuilder(new JacksonAdapter()).

I'll happily add others on request, it`s also quite easy to implement one by oneself.

How to send UTF-8 email?

If not HTML, then UTF-8 is not recommended. koi8-r and windows-1251 only without problems. So use html mail.

$headers['Content-Type']='text/html; charset=UTF-8';
$body='<html><head><meta charset="UTF-8"><title>ESP Notufy - ESP ?????????</title></head><body>'.$text.'</body></html>';


$mail_object=& Mail::factory('smtp',
    array ('host' => $host,
        'auth' => true,
        'username' => $username,
        'password' => $password));
$mail_object->send($recipents, $headers, $body);
}

How to get current class name including package name in Java?

The fully-qualified name is opbtained as follows:

String fqn = YourClass.class.getName();

But you need to read a classpath resource. So use

InputStream in = YourClass.getResourceAsStream("resource.txt");

Cannot use object of type stdClass as array?

The function json_decode() returns an object by default.

You can access the data like this:

var_dump($result->context);

If you have identifiers like from-date (the hyphen would cause a PHP error when using the above method) you have to write:

var_dump($result->{'from-date'});

If you want an array you can do something like this:

$result = json_decode($json, true);

Or cast the object to an array:

$result = (array) json_decode($json);

How do I use Safe Area Layout programmatically?

Swift 4.2 and 5.0. Suppose you wan to add Leading, Trailing, Top and Bottom constraints on viewBg. So, you can use the below code.

let guide = self.view.safeAreaLayoutGuide
viewBg.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
viewBg.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
viewBg.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
viewBg.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true

Convert JavaScript String to be all lower case?

var lowerCaseName = "Your Name".toLowerCase();

How do I perform an insert and return inserted identity with Dapper?

I see answer for sql server, well here it is for MySql using a transaction


    Dim sql As String = "INSERT INTO Empleado (nombres, apepaterno, apematerno, direccion, colonia, cp, municipio, estado, tel, cel, correo, idrol, relojchecadorid, relojchecadorid2, `activo`,`extras`,`rfc`,`nss`,`curp`,`imagen`,sueldoXHra, IMSSCotiza, thumb) VALUES (@nombres, @apepaterno, @apematerno, @direccion, @colonia, @cp, @municipio, @estado, @tel, @cel, @correo, @idrol, @relojchecadorid, @relojchecadorid2, @activo, @extras, @rfc, @nss, @curp, @imagen,@sueldoXHra,@IMSSCotiza, @thumb)"
    
            Using connection As IDbConnection = New MySqlConnection(getConnectionString())
                connection.Open()
                Using transaction = connection.BeginTransaction
                    Dim res = connection.Execute(sql, New With {reg.nombres, reg.apepaterno, reg.apematerno, reg.direccion, reg.colonia, reg.cp, reg.municipio, reg.estado, reg.tel, reg.cel, reg.correo, reg.idrol, reg.relojchecadorid, reg.relojchecadorid2, reg.activo, reg.extras, reg.rfc, reg.nss, reg.curp, reg.imagen, reg.thumb, reg.sueldoXHra, reg.IMSSCotiza}, commandTimeout:=180, transaction:=transaction)
                    lastInsertedId = connection.ExecuteScalar("SELECT LAST_INSERT_ID();", transaction:=transaction)
                    If res > 0 Then 
transaction.Commit()
return true
end if
                    
                End Using
            End Using

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections node in Web.config file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

Installing SciPy with pip

You can also use this in windows with python 3.6 python -m pip install scipy

Fatal error: "No Target Architecture" in Visual Studio

It would seem that _AMD64_ is not defined, since I can't imagine you are compiling for Itanium (_IA64_).

Execute method on startup in Spring

Attention, this is only advised if your runOnceOnStartup method depends on a fully initialized spring context. For example: you wan to call a dao with transaction demarcation

You can also use a scheduled method with fixedDelay set very high

@Scheduled(fixedDelay = Long.MAX_VALUE)
public void runOnceOnStartup() {
    dosomething();
}

This has the advantage that the whole application is wired up (Transactions, Dao, ...)

seen in Scheduling tasks to run once, using the Spring task namespace

Referencing value in a closed Excel workbook using INDIRECT?

In Excel 2016 at least, you can use INDIRECT with a full path reference; the entire reference (including sheet name) needs to be enclosed by ' characters.

So this should work for you:

= INDIRECT("'C:\data\[myExcelFile.xlsm]" & C13 & "'!$A$1")

Note the closing ' in the last string (ie '!$A$1 surrounded by "")

PHP function to make slug (URL string)

Note: I have taken this from wordpress and it works!!

Use it like this:

echo sanitize('testing this link');

Code

//taken from wordpress
function utf8_uri_encode( $utf8_string, $length = 0 ) {
    $unicode = '';
    $values = array();
    $num_octets = 1;
    $unicode_length = 0;

    $string_length = strlen( $utf8_string );
    for ($i = 0; $i < $string_length; $i++ ) {

        $value = ord( $utf8_string[ $i ] );

        if ( $value < 128 ) {
            if ( $length && ( $unicode_length >= $length ) )
                break;
            $unicode .= chr($value);
            $unicode_length++;
        } else {
            if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;

            $values[] = $value;

            if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
                break;
            if ( count( $values ) == $num_octets ) {
                if ($num_octets == 3) {
                    $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
                    $unicode_length += 9;
                } else {
                    $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
                    $unicode_length += 6;
                }

                $values = array();
                $num_octets = 1;
            }
        }
    }

    return $unicode;
}

//taken from wordpress
function seems_utf8($str) {
    $length = strlen($str);
    for ($i=0; $i < $length; $i++) {
        $c = ord($str[$i]);
        if ($c < 0x80) $n = 0; # 0bbbbbbb
        elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
        elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
        elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
        elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
        elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
        else return false; # Does not match any model
        for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
            if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
                return false;
        }
    }
    return true;
}

//function sanitize_title_with_dashes taken from wordpress
function sanitize($title) {
    $title = strip_tags($title);
    // Preserve escaped octets.
    $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
    // Remove percent signs that are not part of an octet.
    $title = str_replace('%', '', $title);
    // Restore octets.
    $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);

    if (seems_utf8($title)) {
        if (function_exists('mb_strtolower')) {
            $title = mb_strtolower($title, 'UTF-8');
        }
        $title = utf8_uri_encode($title, 200);
    }

    $title = strtolower($title);
    $title = preg_replace('/&.+?;/', '', $title); // kill entities
    $title = str_replace('.', '-', $title);
    $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
    $title = preg_replace('/\s+/', '-', $title);
    $title = preg_replace('|-+|', '-', $title);
    $title = trim($title, '-');

    return $title;
}

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

I had the same error message, my mistake was that I had a semicolon at the end of COMMIT TRANSACTION line

python list by value not by reference

When you do b = a you simply create another pointer to the same memory of a, that's why when you append to b , a changes too.

You need to create copy of a and that's done like this:

b = a[:]

Detect the Internet connection is offline?

I was looking for a client-side solution to detect if the internet was down or my server was down. The other solutions I found always seemed to be dependent on a 3rd party script file or image, which to me didn't seem like it would stand the test of time. An external hosted script or image could change in the future and cause the detection code to fail.

I've found a way to detect it by looking for an xhrStatus with a 404 code. In addition, I use JSONP to bypass the CORS restriction. A status code other than 404 shows the internet connection isn't working.

$.ajax({
    url:      'https://www.bing.com/aJyfYidjSlA' + new Date().getTime() + '.html',
    dataType: 'jsonp',
    timeout:  5000,

    error: function(xhr) {
        if (xhr.status == 404) {
            //internet connection working
        }
        else {
            //internet is down (xhr.status == 0)
        }
    }
});

What is the difference between os.path.basename() and os.path.dirname()?

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

Attach the Source in Eclipse of a jar

I am using project is not Spring or spring boot based application. I have multiple subprojects and they are nested one within another. The answers shown here supports on first level of subproject. If I added another sub project for source code attachement, it is not allowing me saying folder already exists error.

Looks like eclipse is out dated IDE. I am using the latest version of Eclipse version 2015-2019. It is killing all my time.

My intension is run the application in debug mode navigate through the sub projects which are added as external dependencies (non modifiable).

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

Git merge develop into feature branch outputs "Already up-to-date" while it's not

Initially my repo said "Already up to date."

MINGW64 (feature/Issue_123) 
$ git merge develop

Output:

Already up to date.

But the code is not up to date & it is showing some differences in some files.

MINGW64 (feature/Issue_123)
$ git diff develop

Output:

diff --git 
a/src/main/database/sql/additional/pkg_etl.sql 
b/src/main/database/sql/additional/pkg_etl.sql
index ba2a257..1c219bb 100644
--- a/src/main/database/sql/additional/pkg_etl.sql
+++ b/src/main/database/sql/additional/pkg_etl.sql

However, merging fixes it.

MINGW64 (feature/Issue_123)
$ git merge origin/develop

Output:

Updating c7c0ac9..09959e3
Fast-forward
3 files changed, 157 insertions(+), 92 deletions(-)

Again I have confirmed this by using diff command.

MINGW64 (feature/Issue_123)
$ git diff develop

No differences in the code now!

Maven package/install without test (skip tests)

In Inllij IDEA there is an option also to skip test goal.

enter image description here

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

I had done below changes for new phpmyadmin4.0.4 in httpd.conf file

<Directory />
    AllowOverride none
    Require all granted
</Directory>

and phpmyadmin.conf

<Directory "c:/wamp/apps/phpmyadmin4.0.4/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Allow,Deny
    Allow from all
</Directory>

and restart my server.

How do I see if Wi-Fi is connected on Android?

val wifi = context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?        
         if (wifi!!.isWifiEnabled) 
              //do action here
    
         else 
             //do action here
    
        
                    

Is there a conditional ternary operator in VB.NET?

iif has always been available in VB, even in VB6.

Dim foo as String = iif(bar = buz, cat, dog)

It is not a true operator, as such, but a function in the Microsoft.VisualBasic namespace.

Pass variables to Ruby script via command line

You can also try out cliqr. Its pretty new and in active development. But there are stable releases ready to be used. Here is the git repo: https://github.com/anshulverma/cliqr

Look into the example folder to get an idea on how it can be used.

Fastest way to reset every value of std::vector<int> to 0

As always when you ask about fastest: Measure! Using the Methods above (on a Mac using Clang):

Method      |  executable size  |  Time Taken (in sec) |
            |  -O0    |  -O3    |  -O0      |  -O3     |  
------------|---------|---------|-----------|----------|
1. memset   | 17 kB   | 8.6 kB  | 0.125     | 0.124    |
2. fill     | 19 kB   | 8.6 kB  | 13.4      | 0.124    |
3. manual   | 19 kB   | 8.6 kB  | 14.5      | 0.124    |
4. assign   | 24 kB   | 9.0 kB  | 1.9       | 0.591    |

using 100000 iterations on an vector of 10000 ints.

Edit: If changeing this numbers plausibly changes the resulting times you can have some confidence (not as good as inspecting the final assembly code) that the artificial benchmark has not been optimized away entirely. Of course it is best to messure the performance under real conditions. end Edit

for reference the used code:

#include <vector>

#define TEST_METHOD 1
const size_t TEST_ITERATIONS = 100000;
const size_t TEST_ARRAY_SIZE = 10000;

int main(int argc, char** argv) {

   std::vector<int> v(TEST_ARRAY_SIZE, 0);

   for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
   #if TEST_METHOD == 1 
      memset(&v[0], 0, v.size() * sizeof v[0]);
   #elif TEST_METHOD == 2
      std::fill(v.begin(), v.end(), 0);
   #elif TEST_METHOD == 3
      for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
         *it = 0;
      }
   #elif TEST_METHOD == 4
      v.assign(v.size(),0);
   #endif
   }

   return EXIT_SUCCESS;
}

Conclusion: use std::fill (because, as others have said its most idiomatic)!

C# version of java's synchronized keyword?

You can use the lock statement instead. I think this can only replace the second version. Also, remember that both synchronized and lock need to operate on an object.

How to change Bootstrap's global default font size?

Add !importent in your css

* {
   font-size: 16px !importent;
   line-height: 2;
}

extracting days from a numpy.timedelta64 value

Suppose you have a timedelta series:

import pandas as pd
from datetime import datetime
z = pd.DataFrame({'a':[datetime.strptime('20150101', '%Y%m%d')],'b':[datetime.strptime('20140601', '%Y%m%d')]})

td_series = (z['a'] - z['b'])

One way to convert this timedelta column or series is to cast it to a Timedelta object (pandas 0.15.0+) and then extract the days from the object:

td_series.astype(pd.Timedelta).apply(lambda l: l.days)

Another way is to cast the series as a timedelta64 in days, and then cast it as an int:

td_series.astype('timedelta64[D]').astype(int)

Excel VBA Run Time Error '424' object required

The first code line, Option Explicit means (in simple terms) that all of your variables have to be explicitly declared by Dim statements. They can be any type, including object, integer, string, or even a variant.

This line: Dim envFrmwrkPath As Range is declaring the variable envFrmwrkPath of type Range. This means that you can only set it to a range.

This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value is attempting to set the Range type variable to a specific Value that is in cell D6. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.

I'm assuming you want the value stored in a variable. Try something like this:

Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value

This assumes you have a number (like 5) in cell D6. Now your variable will have the value.

For simplicity sake of learning, you can remove or comment out the Option Explicit line and VBA will try to determine the type of variables at run time.


Try this to get through this part of your code

Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String

Uncaught SyntaxError: Invalid or unexpected token

You should pass @item.email in quotes then it will be treated as string argument

<td><a href ="#"  onclick="Getinfo('@item.email');" >6/16/2016 2:02:29 AM</a>  </td>

Otherwise, it is treated as variable thus error is generated.

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

Load CSV data into MySQL in Python

I think you have to do mydb.commit() all the insert into.

Something like this

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('students.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO testcsv(names, \
          classes, mark )' \
          'VALUES("%s", "%s", "%s")', 
          row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"

"Are you missing an assembly reference?" compile error - Visual Studio

Right-click the assembly reference in the solution explorer, properties, disable the "Specific Version" option.

What does the servlet <load-on-startup> value signify

It is simple as you don't even expect.

If the value is positive it loaded when the container starts

If the value is not positive than the servelet is loaded when the request is made.

What is the format for the PostgreSQL connection string / URL?

the connection url for postgres syntax:

"Server=host ipaddress;Port=5432;Database=dbname;User Id=userid;Password=password;

example:

"Server=192.168.1.163;Port=5432;Database=postgres;User Id=postgres;Password=root;

Sorting std::map using value

Another solution would be the usage of std::make_move_iterator to build a new vector (C++11 )

    int main(){

      std::map<std::string, int> map;
       //Populate map

      std::vector<std::pair<std::string, int>> v {std::make_move_iterator(begin(map)),
                                      std::make_move_iterator(end(map))};
       // Create a vector with the map parameters

       sort(begin(v), end(v),
             [](auto p1, auto p2){return p1.second > p2.second;});
       // Using sort + lambda function to return an ordered vector 
       // in respect to the int value that is now the 2nd parameter 
       // of our newly created vector v
  }

Foreach in a Foreach in MVC View

Try this:

It looks like you are looping for every product each time, now this is looping for each product that has the same category ID as the current category being looped

<div id="accordion1" style="text-align:justify">
@using (Html.BeginForm())
{
    foreach (var category in Model.Categories)
    {
        <h3><u>@category.Name</u></h3>

        <div>
            <ul>    
                @foreach (var product in Model.Product.Where(m=> m.CategoryID= category.CategoryID)
                {
                    <li>
                        @product.Title
                        @if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
                        {
                            @Html.Raw(" - ")  
                            @Html.ActionLink("Edit", "Edit", new { id = product.ID })
                        }
                        <ul>
                            <li>
                                @product.Description
                            </li>
                        </ul>
                    </li>
                }
            </ul>
        </div>
    }
}  

Detect if checkbox is checked or unchecked in Angular.js ng-change event

The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]

How to insert the current timestamp into MySQL database using a PHP insert query

Don't like any of those solutions.

this is how i do it:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='" 
            . sqlEsc($somename) . "' ;";

then i use my own sqlEsc function:

function sqlEsc($val) 
{
    global $mysqli;
    return mysqli_real_escape_string($mysqli, $val);
}

How to convert hashmap to JSON object in Java

Better be late than never. I used GSON to convert list of HashMap to string if in case you want to have a serialized list.

List<HashMap<String, String>> list = new ArrayList<>();
HashMap<String,String> hashMap = new HashMap<>();
hashMap.add("key", "value");
hashMap.add("key", "value");
hashMap.add("key", "value");
list.add(hashMap);

String json = new Gson().toJson(list);

This json produces [{"key":"value","key":"value","key":"value"}]

Picasso v/s Imageloader v/s Fresco vs Glide

I am one of the engineers on the Fresco project. So obviously I'm biased.

But you don't have to take my word for it. We've released a sample app that allows you to compare the performance of five libraries - Fresco, Picasso, UIL, Glide, and Volley Image Loader - side by side. You can get it at our GitHub repo.

I should also point out that Fresco is available on Maven Central, as com.facebook.fresco:fresco.

Fresco offers features that Picasso, UIL, and Glide do not yet have:

  1. Images aren't stored in the Java heap, but in the ashmem heap. Intermediate byte buffers are also stored in the native heap. This leaves a lot more memory available for applications to use. It reduces the risk of OutOfMemoryErrors. It also reduces the amount of garbage collection apps have to do, leading to better performance.
  2. Progressive JPEG images can be streamed, just like in a web browser.
  3. Images can be cropped around any point, not just the center.
  4. JPEG images can be resized natively. This avoids the problem of OOMing while trying to downsize an image.

There are many others (see our documentation), but these are the most important.

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

You need to set up a local repository that will host such libraries. There are a number of projects that do exactly that. For example Artifactory.

Best HTML5 markup for sidebar

The ASIDE has since been modified to include secondary content as well.

HTML5 Doctor has a great writeup on it here: http://html5doctor.com/aside-revisited/

Excerpt:

With the new definition of aside, it’s crucial to remain aware of its context. >When used within an article element, the contents should be specifically related >to that article (e.g., a glossary). When used outside of an article element, the >contents should be related to the site (e.g., a blogroll, groups of additional >navigation, and even advertising if that content is related to the page).

How to add Google Maps Autocomplete search box?

Follow the below code.

Add this to your TS file.

declare this, top of your class.

declare var google;

declare the view child for Map and the input.

@ViewChild('mapElement', {static: true}) mapNativeElement: ElementRef;
@ViewChild('autoCompleteInput', {static: true}) inputNativeElement: any;

this method is run on ngOnInit() event or ngAfterViewInit() event.

autoComplete() {
    const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
      center: {lat: -33.8688, lng: 151.2093},
      zoom: 7
    });

    const infowindow = new google.maps.InfoWindow();
    const infowindowContent = document.getElementById('infowindow-content');

    infowindow.setContent(infowindowContent);

    const marker = new google.maps.Marker({
      map: map,
      anchorPoint: new google.maps.Point(0, -29)
    });
    const autocomplete = new google.maps.places.Autocomplete(this.inputNativeElement.nativeElement as HTMLInputElement);
    autocomplete.addListener('place_changed', () => {
      infowindow.close();
      marker.setVisible(false);
      const place = autocomplete.getPlace();

      let cus_location = {
        lat: place.geometry.location.lat(),
        long: place.geometry.location.lng()
      }

      console.log('place data :................', cus_location); 
      localStorage.setItem('LOC_DATA', this.helper.encryptData(cus_location));

      if (!place.geometry) {
        // User entered the name of a Place that was not suggested and
        // pressed the Enter key, or the Place Details request failed.
        window.alert('No details available for input: ' + place.name );
        return;
      }

      if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
      } else {
        map.setCenter(place.geometry.location);
        map.setZoom(17);  // Why 17? Because it looks good.
      }

      marker.setPosition(place.geometry.location);
      marker.setVisible(true);
      let address = '';
      if (place.address_components) {
        address = [
          (place.address_components[0] && place.address_components[0].short_name || ''),
          (place.address_components[1] && place.address_components[1].short_name || ''),
          (place.address_components[2] && place.address_components[2].short_name || '')
        ].join(' ');
      }

      if(infowindowContent){
        infowindowContent.children['place-icon'].src = place.icon;
        infowindowContent.children['place-name'].textContent = place.name;
        infowindowContent.children['place-address'].textContent = address;
      } 

      infowindow.open(map, marker);
    });

  }

calling the method on ngAfterViewInit.

ngAfterViewInit(): void {
    this.autoComplete();
  }

And this is the HTML code. please modify as per your need.

<ion-content fullscreen>
    <div class="location-col">


        <div class="google-map">
            <!-- <img src="../../assets/images/google-map.jpg" alt=""> -->
            <div #mapElement id="map"></div>
        </div>


        <div class="location-info">
            <h2>Where is your car located?</h2>
            <p>Enter address manually or click location detector icon to use current address.</p>
            <div class="form-group">

                <div class="location-row">
                    <input type="text" #autoCompleteInput class="location-input" [(ngModel)]="search_location" placeholder="Search location">
                    <span class="location-icon" (click)="getCurrentLocation()">
                        <img src="../../assets/images/location-icon.svg" alt="">
                    </span>
                </div>

                <button type="button" class="location-search-btn" (click)="goToVendorSearch()">
                    <i class="fa fa-angle-right"></i>
                </button>

            </div>
        </div>
    </div>
</ion-content>

self referential struct definition?

Lets go through basic definition of typedef. typedef use to define an alias to an existing data type either it is user defined or inbuilt.

typedef <data_type> <alias>;

for example

typedef int scores;

scores team1 = 99;

Confusion here is with the self referential structure, due to a member of same data type which is not define earlier. So In standard way you can write your code as :-

//View 1
typedef struct{ bool isParent; struct Cell* child;} Cell;

//View 2
typedef struct{
  bool isParent;
  struct Cell* child;
} Cell;

//Other Available ways, define stucture and create typedef
struct Cell {
  bool isParent;
  struct Cell* child;
};

typedef struct Cell Cell;

But last option increase some extra lines and words with usually we don't want to do (we are so lazy you know ;) ) . So prefer View 2.

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

I had single quotes in my

var map = new google.maps.Map( document.getElementById('map_canvas') );

and replaced them with double quotes

var map = new google.maps.Map( document.getElementById("map_canvas") );

This did the trick for me.

Sum columns with null values in oracle

select type, craft, sum(nvl(regular,0) + nvl(overtime,0)) as total_hours
from hours_t
group by type, craft
order by type, craft

Embed a PowerPoint presentation into HTML

I got so sick of trying all of the different options to web host a power point that were flaky or required flash so I rolled my own.

My solution uses a very simple javascript function to simply scroll / replace a image tag with GIFs that I saved from the Power Point presentation itself.

  1. In the power point presentation click Save As and select GIF. Pick the quality you want to display the presentation at. Power Point will save one GIF image for each slide and name them Slide1.GIF, Slide2.GIF, etc.....

  2. Create a HTML page and add a image tag to display the Power point GIF images.

    <img src="Slide1.GIF" id="mainImage" name="mainImage" width="100%" height="100%" alt="">
    
  3. Add some first, previous, next and last clickable objects with the onClick action as below:

    <a href="#" onclick="swapImage(0);"><img src="/images/first.png" border=0 alt="First"></a>
    <a href="#" onclick="swapImage(currentIndex-1);"><img src="/images/left.png" border=0 alt="Back"></a>
    <a href="#" onclick="swapImage(currentIndex+1);"><img src="/images/right.png" border=0 alt="Next"></a>
    <a href="#" onclick="swapImage(maxIndex);"><img src="/images/last.png" border=0 alt="Last"></a>
    
  4. Finally, add the below javascript function that when called grabs the next Slide.GIF image and displays it to the img tag.

    <script type="text/javascript">
        //Initilize start value to 1 'For Slide1.GIF'
        var currentIndex = 1;
    
        //NOTE: Set this value to the number of slides you have in the presentation.
        var maxIndex=12;
    
        function swapImage(imageIndex){
            //Check if we are at the last image already, return if we are.
            if(imageIndex>maxIndex){
                currentIndex=maxIndex;
                return;
            }
    
            //Check if we are at the first image already, return if we are.
            if(imageIndex<1){
                currentIndex=1;
                return;
            }
    
            currentIndex=imageIndex;
            //Otherwise update mainImage
            document.getElementById("mainImage").src='Slide' +  currentIndex  + '.GIF';
            return;
        }
    </script>
    

Make sure the GIFs are reachable from the HTMl page. They are by default expected to be in the same directory but you should be able to see the logic and how to set to a image directory if required

I have training material up for my company that uses this technique at http://www.vanguarddata.com.au so before you spend any time trying it out you are welcome to look at in action.

I hope this helps someone else out there who is having as much headaches with this as I did.....

Disabling SSL Certificate Validation in Spring RestTemplate

Complete code to disable SSL hostname verifier,

RestTemplate restTemplate = new RestTemplate();
//to disable ssl hostname verifier
restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory() {
   @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setHostnameVerifier(new NoopHostnameVerifier());
        }
        super.prepareConnection(connection, httpMethod);
    }
});

How to use continue in jQuery each() loop?

return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".

Creating a class object in c++

Example example;

Here example is an object on the stack.

Example* example=new Example();

This could be broken into:

Example* example;
....
example=new Example();

Here the first statement creates a variable example which is a "pointer to Example". When the constructor is called, memory is allocated for it on the heap (dynamic allocation). It is the programmer's responsibility to free this memory when it is no longer needed. (C++ does not have garbage collection like java).

RSA Public Key format

You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ---- to -----BEGIN RSA PUBLIC KEY----- and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).

This article has a good explanation about both formats.

What you get in an RSA PUBLIC KEY is closer to the content of a PUBLIC KEY, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse and -strparse 19, as described in this answer.

EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER:

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim: INTEGER           :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
  265:d=1  hl=2 l=   3 prim: INTEGER           :010001

To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:

   The "ssh-rsa" key format has the following specific encoding:

      string    "ssh-rsa"
      mpint     e
      mpint     n

For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61. The first four bytes (00 00 00 07) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61=ssh-rsa, followed by the exponent of length 1 (00 00 00 01 25) and the modulus of length 256 (00 00 01 00 7f ...).

public static const in TypeScript

Meanwhile this can be solved through a decorator in combination with Object.freeze or Object.defineProperty, I'm using this, it's a little bit prettier than using tons of getters. You can copy/paste this directly TS Playground to see it in action. - There are two options


Make individual fields "final"

The following decorator converts both, annotated static and non-static fields to "getter-only-properties".

Note: If an instance-variable with no initial value is annotated @final, then the first assigned value (no matter when) will be the final one.

// example
class MyClass {
    @final
    public finalProp: string = "You shall not change me!";

    @final
    public static FINAL_FIELD: number = 75;

    public static NON_FINAL: string = "I am not final."
}

var myInstance: MyClass = new MyClass();
myInstance.finalProp = "Was I changed?";
MyClass.FINAL_FIELD = 123;
MyClass.NON_FINAL = "I was changed.";

console.log(myInstance.finalProp);  // => You shall not change me!
console.log(MyClass.FINAL_FIELD);   // => 75
console.log(MyClass.NON_FINAL);     // => I was changed.

The Decorator: Make sure you include this in your code!

/**
* Turns static and non-static fields into getter-only, and therefor renders them "final".
* To use simply annotate the static or non-static field with: @final
*/
function final(target: any, propertyKey: string) {
    const value: any = target[propertyKey];
    // if it currently has no value, then wait for the first setter-call
    // usually the case with non-static fields
    if (!value) {
        Object.defineProperty(target, propertyKey, {
            set: function (value: any) {
                Object.defineProperty(this, propertyKey, {
                    get: function () {
                        return value;
                    },
                    enumerable: true,
                    configurable: false
                });
            },
            enumerable: true,
            configurable: true
        });
    } else { // else, set it immediatly
        Object.defineProperty(target, propertyKey, {
            get: function () {
                return value;
            },
            enumerable: true
        });
    }
}

As an alternative to the decorator above, there would also be a strict version of this, which would even throw an Error when someone tried to assign some value to the field with "use strict"; being set. (This is only the static part though)

/**
 * Turns static fields into getter-only, and therefor renders them "final".
 * Also throws an error in strict mode if the value is tried to be touched.
 * To use simply annotate the static field with: @strictFinal
 */
function strictFinal(target: any, propertyKey: string) {
    Object.defineProperty(target, propertyKey, {
        value: target[propertyKey],
        writable: false,
        enumerable: true
    });
}

Make every static field "final"

Possible Downside: This will only work for ALL statics of that class or for none, but cannot be applied to specific statics.

/**
* Freezes the annotated class, making every static 'final'.
* Usage:
* @StaticsFinal
* class MyClass {
*      public static SOME_STATIC: string = "SOME_STATIC";
*      //...
* }
*/
function StaticsFinal(target: any) {
    Object.freeze(target);
}
// Usage here
@StaticsFinal
class FreezeMe {
    public static FROZEN_STATIC: string = "I am frozen";
}

class EditMyStuff {
    public static NON_FROZEN_STATIC: string = "I am frozen";
}

// Test here
FreezeMe.FROZEN_STATIC = "I am not frozen.";
EditMyStuff.NON_FROZEN_STATIC = "I am not frozen.";

console.log(FreezeMe.FROZEN_STATIC); // => "I am frozen."
console.log(EditMyStuff.NON_FROZEN_STATIC); // => "I am not frozen."

Python how to plot graph sine wave

Yet another way to plot the sine wave.

import numpy as np
import matplotlib
matplotlib.use('TKAgg') #use matplotlib backend TKAgg (optional)
import matplotlib.pyplot as plt

t = np.linspace(0.0, 5.0, 50000)       # time axis
sig = np.sin(t)
plt.plot(t,sig)

Android Studio: Can't start Git

Use bin folder and exe instead. Path will be C:\Program Files (x86)\Git\bin\git.exe

Also sometimes it doesn't work if there are blank spaces in path name as in your program files directory name.

In that case, copy the whole git folder to root of partition and then link studio to it

How can I convert spaces to tabs in Vim or Linux?

Simple Python Script:

import os

SOURCE_ROOT = "ROOT DIRECTORY - WILL CONVERT ALL UNDERNEATH"

for root, dirs, files in os.walk(SOURCE_ROOT):
    for f in files:
        fpath = os.path.join(root,f)
        assert os.path.exists(fpath)
        data = open(fpath, "r").read()
        data = data.replace("    ", "\t")
        outfile = open(fpath, "w")
        outfile.write(data)
        outfile.close()

How to remove padding around buttons in Android?

That's not padding, it's the shadow around the button in its background drawable. Create your own background and it will disappear.

TCP: can two different sockets share a port?

No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.

Increasing the Command Timeout for SQL command

Setting command timeout to 2 minutes.

 scGetruntotals.CommandTimeout = 120;

but you can optimize your stored Procedures to decrease that time! like

  • removing courser or while and etc
  • using paging
  • using #tempTable and @variableTable
  • optimizing joined tables

Jquery onclick on div

Make sure it's within a document ready tagAlternatively, try using .live

$(document).ready(function(){

    $('#content').live('click', function(e) {  
        alert(1);
    });
});

Example:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    $('#content').click(function(e) {  _x000D_
      alert(1);_x000D_
    });_x000D_
});
_x000D_
#content {_x000D_
    padding: 20px;_x000D_
    background: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id="content">Hello world</div>
_x000D_
_x000D_
_x000D_

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

$('#content').on( "click", function() {
    alert(1);
});

Fixed page header overlaps in-page anchors

Just discovered another pure CSS solution that worked like a charme for me!

html {
  scroll-padding-top: 80px; /* height of your sticky header */
}

Found on this site!

Adding <script> to WordPress in <head> element

For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here.

Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.

Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.

Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.

Something along the following in a plugin file is what you are looking for:

<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI: 
Plugin URI: 
*/

function $yourJS() {
    wp_enqueue_script(
        'custom_script',
        plugins_url( '/js/your-script.js', __FILE__ ),
        array( 'jquery' )
    );
}
 add_action( 'wp_enqueue_scripts',  '$yourJS' );
 add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );

 function prefix_add_my_stylesheet() {
    wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
    wp_enqueue_style( 'prefix-style' );
  }

?>

Structure your folders as follows:

Plugin Folder
  |_ css folder
  |_ js folder
  |_ plugin.php ...contains the above code - modified of course ;D

Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

Better way to generate array of all letters in the alphabet

Finally you are getting a char array with alphabet. Why did you do so hard way using a loop ?

It is just

char[] alphabet=new char[]{'a','b',.........,'z'}

Better way of getting time in milliseconds in javascript?

I know this is a pretty old thread, but to keep things up to date and more relevant, you can use the more accurate performance.now() functionality to get finer grain timing in javascript.

window.performance = window.performance || {};
performance.now = (function() {
    return performance.now       ||
        performance.mozNow    ||
        performance.msNow     ||
        performance.oNow      ||
        performance.webkitNow ||            
        Date.now  /*none found - fallback to browser default */
})();

Java double.MAX_VALUE?

Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).

This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.

Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).

How do I tell CMake to link in a static library in the source directory?

If you don't want to include the full path, you can do

add_executable(main main.cpp)
target_link_libraries(main bingitup)

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp)

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/)

Android - how do I investigate an ANR?

Consider using the ANR-Watchdog library to accurately track and capture ANR stack traces in a high level of detail. You can then send them to your crash reporting library. I recommend using setReportMainThreadOnly() in this scenario. You can either make the app throw a non-fatal exception of the freeze point, or make the app force quit when the ANR happens.

Note that the standard ANR reports sent to your Google Play Developer console are often not accurate enough to pinpoint the exact problem. That's why a third-party library is needed.

How do I return a proper success/error message for JQuery .ajax() using PHP?

In order to build an AJAX webservice, you need TWO files :

  • A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
  • A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)

So, first you call your webservice using this JQuery syntax, in the JavaScript file :

$.ajax({
     url : 'mywebservice.php',
     type : 'POST',
     data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
     dataType : 'json',
     success: function (data) {
          alert("The file is "+data.fichierZIP);
     },
     error: function(data) {
          //console.log(data);
          var responseText=JSON.parse(data.responseText);
          alert("Error(s) while building the ZIP file:\n"+responseText.messages);
     }
});

Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:

<?php
    //...
    //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
    //$errors is a string that may contain an error message while preparing the ZIP file
    //In the end, I check if there has been an error, and if so, I return an error object
    //...

    if ($errors==''){
        //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['ZIPFILENAME'] = basename($filename); 
        print json_encode($result);
    } else {
        //if there is an error, you should return a special header, followed by another JSON object
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['messages'] = $errors;
        //feel free to add other information like $result['errorcode']
        die(json_encode($result));
    }
?>

Auto height of div

make sure the content inside your div ended with clear:both style

What encoding/code page is cmd.exe using?

I've been frustrated for long by Windows code page issues, and the C programs portability and localisation issues they cause. The previous posts have detailed the issues at length, so I'm not going to add anything in this respect.

To make a long story short, eventually I ended up writing my own UTF-8 compatibility library layer over the Visual C++ standard C library. Basically this library ensures that a standard C program works right, in any code page, using UTF-8 internally.

This library, called MsvcLibX, is available as open source at https://github.com/JFLarvoire/SysToolsLib. Main features:

  • C sources encoded in UTF-8, using normal char[] C strings, and standard C library APIs.
  • In any code page, everything is processed internally as UTF-8 in your code, including the main() routine argv[], with standard input and output automatically converted to the right code page.
  • All stdio.h file functions support UTF-8 pathnames > 260 characters, up to 64 KBytes actually.
  • The same sources can compile and link successfully in Windows using Visual C++ and MsvcLibX and Visual C++ C library, and in Linux using gcc and Linux standard C library, with no need for #ifdef ... #endif blocks.
  • Adds include files common in Linux, but missing in Visual C++. Ex: unistd.h
  • Adds missing functions, like those for directory I/O, symbolic link management, etc, all with UTF-8 support of course :-).

More details in the MsvcLibX README on GitHub, including how to build the library and use it in your own programs.

The release section in the above GitHub repository provides several programs using this MsvcLibX library, that will show its capabilities. Ex: Try my which.exe tool with directories with non-ASCII names in the PATH, searching for programs with non-ASCII names, and changing code pages.

Another useful tool there is the conv.exe program. This program can easily convert a data stream from any code page to any other. Its default is input in the Windows code page, and output in the current console code page. This allows to correctly view data generated by Windows GUI apps (ex: Notepad) in a command console, with a simple command like: type WINFILE.txt | conv

This MsvcLibX library is by no means complete, and contributions for improving it are welcome!

IntelliJ and Tomcat.. Howto..?

Please verify that the required plug-ins are enabled in Settings | Plugins, most likely you've disabled several of them, that's why you don't see all the facet options.

For the step by step tutorial, see: Creating a simple Web application and deploying it to Tomcat.

X11/Xlib.h not found in Ubuntu

Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.

A simple get started:

Create test.cpp: (This will be built and run to verify you got things set up right.)

#include <X11/Xlib.h>
#include <unistd.h>


main()
{
  // Open a display.
  Display *d = XOpenDisplay(0);

  if ( d )
    {
      // Create the window
      Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
                   100, 0, CopyFromParent, CopyFromParent,
                   CopyFromParent, 0, 0);

      // Show the window
      XMapWindow(d, w);
      XFlush(d);

      // Sleep long enough to see the window.
      sleep(10);
    }
  return 0;
}

(Source: LinuxGazette)

Try: g++ test.cpp -lX11 If it builds to a.out, try running it. If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.

If your response is:

    test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
    compilation terminated.

you need to install X11 development libraries. sudo apt-get install libx11-dev

Retry g++ test.cpp -lX11

If it works, you're golden.

Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb

find index of an int in a list

Use the .IndexOf() method of the list. Specs for the method can be found on MSDN.

How to find pg_config path

I had exactly the same error, but I installed postgreSQL through brew and re-run the original command and it worked perfectly :

brew install postgresql

Regular expression containing one word or another

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

How to get previous month and year relative to today, using strtotime and date?

strtotime have second timestamp parameter that make the first parameter relative to second parameter. So you can do this:

date('Y-m', strtotime('-1 month', time()))

android pinch zoom

I have created a project for basic pinch-zoom that supports Android 2.1+

Available here

How do you detect where two line segments intersect?

C and Objective-C

Based on Gareth Rees' answer

const AGKLine AGKLineZero = (AGKLine){(CGPoint){0.0, 0.0}, (CGPoint){0.0, 0.0}};

AGKLine AGKLineMake(CGPoint start, CGPoint end)
{
    return (AGKLine){start, end};
}

double AGKLineLength(AGKLine l)
{
    return CGPointLengthBetween_AGK(l.start, l.end);
}

BOOL AGKLineIntersection(AGKLine l1, AGKLine l2, CGPoint *out_pointOfIntersection)
{
    // http://stackoverflow.com/a/565282/202451

    CGPoint p = l1.start;
    CGPoint q = l2.start;
    CGPoint r = CGPointSubtract_AGK(l1.end, l1.start);
    CGPoint s = CGPointSubtract_AGK(l2.end, l2.start);
    
    double s_r_crossProduct = CGPointCrossProductZComponent_AGK(r, s);
    double t = CGPointCrossProductZComponent_AGK(CGPointSubtract_AGK(q, p), s) / s_r_crossProduct;
    double u = CGPointCrossProductZComponent_AGK(CGPointSubtract_AGK(q, p), r) / s_r_crossProduct;
    
    if(t < 0 || t > 1.0 || u < 0 || u > 1.0)
    {
        if(out_pointOfIntersection != NULL)
        {
            *out_pointOfIntersection = CGPointZero;
        }
        return NO;
    }
    else
    {
        if(out_pointOfIntersection != NULL)
        {
            CGPoint i = CGPointAdd_AGK(p, CGPointMultiply_AGK(r, t));
            *out_pointOfIntersection = i;
        }
        return YES;
    }
}

CGFloat CGPointCrossProductZComponent_AGK(CGPoint v1, CGPoint v2)
{
    return v1.x * v2.y - v1.y * v2.x;
}

CGPoint CGPointSubtract_AGK(CGPoint p1, CGPoint p2)
{
    return (CGPoint){p1.x - p2.x, p1.y - p2.y};
}

CGPoint CGPointAdd_AGK(CGPoint p1, CGPoint p2)
{
    return (CGPoint){p1.x + p2.x, p1.y + p2.y};
}

CGFloat CGPointCrossProductZComponent_AGK(CGPoint v1, CGPoint v2)
{
    return v1.x * v2.y - v1.y * v2.x;
}

CGPoint CGPointMultiply_AGK(CGPoint p1, CGFloat factor)
{
    return (CGPoint){p1.x * factor, p1.y * factor};
}

Many of the functions and structs are private, but you should pretty easy be able to know what's going on. This is public on this repo https://github.com/hfossli/AGGeometryKit/

Get list of a class' instance methods

$ irb --simple-prompt

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3

AngularJS multiple filter with custom filter function

In view file (HTML or EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

and In Controller

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}

How to add an element to Array and shift indexes?

System.arraycopy is more performant but tricky to get right due to indexes calculations. Better stick with jrad answer or ArrayList if you don't have performance requirements.

public static int[] insert(
    int[] array, int elementToInsert, int index) {
  int[] result = new int[array.length + 1];
  // copies first part of the array from the start up until the index
  System.arraycopy(
      array /* src */,
      0 /* srcPos */,
      result /* dest */,
      0 /* destPos */,
      index /* length */);
  // copies second part from the index up until the end shifting by 1 to the right
  System.arraycopy(
      array /* src */,
      index /* srcPos */,
      result /* dest */,
      index + 1 /* destPos */,
      array.length - index /* length */);
  result[index] = elementToInsert;
  return result;
}

And JUnit4 test to check it works as expected.

@Test
public void shouldInsertCorrectly() {
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{1, 3}, 2, 1));
  Assert.assertArrayEquals(
      new int[]{1}, insert(new int[]{}, 1, 0));
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{2, 3}, 1, 0));
  Assert.assertArrayEquals(
      new int[]{1, 2, 3}, insert(new int[]{1, 2}, 3, 2));
}

How to strip a specific word from a string?

Use str.replace.

>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'

Alternatively use re and use regular expressions. This will allow the removal of leading/trailing spaces.

>>> import re
>>> papa = 'papa is a good man'
>>> app = 'app is important'
>>> papa3 = 'papa is a papa, and papa'
>>>
>>> patt = re.compile('(\s*)papa(\s*)')
>>> patt.sub('\\1mama\\2', papa)
'mama is a good man'
>>> patt.sub('\\1mama\\2', papa3)
'mama is a mama, and mama'
>>> patt.sub('', papa3)
'is a, and'

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

How do you check in python whether a string contains only numbers?

As pointed out in this comment How do you check in python whether a string contains only numbers? the isdigit() method is not totally accurate for this use case, because it returns True for some digit-like characters:

>>> "\u2070".isdigit() # unicode escaped 'superscript zero' 
True

If this needs to be avoided, the following simple function checks, if all characters in a string are a digit between "0" and "9":

import string

def contains_only_digits(s):
    # True for "", "0", "123"
    # False for "1.2", "1,2", "-1", "a", "a1"
    for ch in s:
        if not ch in string.digits:
            return False
    return True

Used in the example from the question:

if len(isbn) == 10 and contains_only_digits(isbn):
    print ("Works")

How do I prevent CSS inheritance?

Short answer is: No, it's not possible to prevent CSS inheritance. You can only override the styles that are set on the parents. See the spec:

Every element in an HTML document will inherit all inheritable properties from its parent except the root element (html), which doesn’t have a parent. -W3C

Apart from overriding every single inherited property. You can also use initial keyword, e.g. color: initial;. It also can be used together with all, e.g. all: initial;, that will reset all properties at once. Example:

_x000D_
_x000D_
.container {_x000D_
  color: blue;_x000D_
  font-style: italic;_x000D_
}_x000D_
.initial {_x000D_
  all: initial;_x000D_
}
_x000D_
<div class="container">_x000D_
  The quick brown <span class="initial">fox</span> jumps over the lazy dog_x000D_
</div>
_x000D_
_x000D_
_x000D_

Browser support tables according to Can I use...

  • all (Currently no support in both IE and Edge, others are good)
  • initial (Currently no support in IE, others are good)

You may find it useful by using direct children selector > in some cases. Example:

_x000D_
_x000D_
.list > li {_x000D_
  border: 1px solid red;_x000D_
  color: blue;_x000D_
}
_x000D_
<ul class="list">_x000D_
  <li>_x000D_
    <span>HEADING 1</span>_x000D_
    <ul>_x000D_
      <li>sub-heading A</li>_x000D_
      <li>sub-heading B</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
  <li>_x000D_
    <span>HEADING 2</span>_x000D_
    <ul>_x000D_
      <li>sub-heading A</li>_x000D_
      <li>sub-heading B</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

The border style has been applied only to the direct children <li>s, as border is an non-inherited property. But text color has been applied to all the children, as color is an inherited property.

Therefore, > selector would be only useful with non-inherited properties, when it comes to preventing inheritance.

Android- create JSON Array and JSON Object

Here's a simpler (but not so short) version which doesn't require try-catch:

Map<String, String> data = new HashMap<>();
data.put("user", "[email protected]");
data.put("pass", "123");

JSONObject jsonData = new JSONObject(data);

If you want to add a jsonObject into a field, you can do this way:

data.put("socialMedia", (new JSONObject()).put("facebookId", "1174989895893400"));
data.put("socialMedia", (new JSONObject()).put("googleId", "106585039098745627377"));

Unfortunately it needs a try-catch because of the put() method.

IF you want to avoid try-catch again (not very recommended, but it's ok if you can guarantee well formated json strings), you might do this way:

data.put("socialMedia", "{ 'facebookId': '1174989895893400' }");

You can do the same about JsonArrays and so on.

Cheers.

How to subtract days from a plain Date?

var daysToSubtract = 3;
$.datepicker.formatDate('yy/mm/dd', new Date() - daysToSubtract) ;

How to set Spring profile from system variable?

My solution is to set the environment variable as spring.profiles.active=development. So that all applications running in that machine will refer the variable and start the application. The order in which spring loads a properties as follows

application.properties
system properties
environment variable

%Like% Query in spring JpaRepository

You can have one alternative of using placeholders as:

@Query("Select c from Registration c where c.place LIKE  %?1%")
List<Registration> findPlaceContainingKeywordAnywhere(String place);

XML Serialize generic list of serializable objects

Below is a Util class in my project:

namespace Utils
{
    public static class SerializeUtil
    {
        public static void SerializeToFormatter<F>(object obj, string path) where F : IFormatter, new()
        {
            if (obj == null)
            {
                throw new NullReferenceException("obj Cannot be Null.");
            }

            if (obj.GetType().IsSerializable == false)
            {
                //  throw new 
            }
            IFormatter f = new F();
            SerializeToFormatter(obj, path, f);
        }

        public static T DeserializeFromFormatter<T, F>(string path) where F : IFormatter, new()
        {
            T t;
            IFormatter f = new F();
            using (FileStream fs = File.OpenRead(path))
            {
                t = (T)f.Deserialize(fs);
            }
            return t;
        }

        public static void SerializeToXML<T>(string path, object obj)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (FileStream fs = File.Create(path))
            {
                xs.Serialize(fs, obj);
            }
        }

        public static T DeserializeFromXML<T>(string path)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (FileStream fs = File.OpenRead(path))
            {
                return (T)xs.Deserialize(fs);
            }
        }

        public static T DeserializeFromXml<T>(string xml)
        {
            T result;

            var ser = new XmlSerializer(typeof(T));
            using (var tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }


        private static void SerializeToFormatter(object obj, string path, IFormatter formatter)
        {
            using (FileStream fs = File.Create(path))
            {
                formatter.Serialize(fs, obj);
            }
        }
    }
}

How do I measure request and response times at once using cURL?

From this brilliant blog post... https://blog.josephscott.org/2011/10/14/timing-details-with-curl/

cURL supports formatted output for the details of the request (see the cURL manpage for details, under -w, –write-out <format>). For our purposes we’ll focus just on the timing details that are provided. Times below are in seconds.

  1. Create a new file, curl-format.txt, and paste in:

         time_namelookup:  %{time_namelookup}s\n
            time_connect:  %{time_connect}s\n
         time_appconnect:  %{time_appconnect}s\n
        time_pretransfer:  %{time_pretransfer}s\n
           time_redirect:  %{time_redirect}s\n
      time_starttransfer:  %{time_starttransfer}s\n
                         ----------\n
              time_total:  %{time_total}s\n
    
  2. Make a request:

     curl -w "@curl-format.txt" -o /dev/null -s "http://wordpress.com/"
    

Or on Windows, it's...

    curl -w "@curl-format.txt" -o NUL -s "http://wordpress.com/"

What this does:

-w "@curl-format.txt" tells cURL to use our format file
-o /dev/null redirects the output of the request to /dev/null
-s tells cURL not to show a progress meter
"http://wordpress.com/" is the URL we are requesting. Use quotes particularly if your URL has "&" query string parameters


And here is what you get back:

   time_namelookup:  0.001s
      time_connect:  0.037s
   time_appconnect:  0.000s
  time_pretransfer:  0.037s
     time_redirect:  0.000s
time_starttransfer:  0.092s
                   ----------
        time_total:  0.164s

Make a Linux/Mac shortcut (alias)

alias curltime="curl -w \"@$HOME/.curl-format.txt\" -o /dev/null -s "

Then you can simply call...

curltime wordpress.org

Thanks to commenter Pete Doyle!


Make a Linux/Mac stand-alone script

This script does not require a separate .txt file to contain the formatting.

Create a new file, curltime, somewhere in your executable path, and paste in:

#!/bin/bash

curl -w @- -o /dev/null -s "$@" <<'EOF'
    time_namelookup:  %{time_namelookup}\n
       time_connect:  %{time_connect}\n
    time_appconnect:  %{time_appconnect}\n
   time_pretransfer:  %{time_pretransfer}\n
      time_redirect:  %{time_redirect}\n
 time_starttransfer:  %{time_starttransfer}\n
                    ----------\n
         time_total:  %{time_total}\n
EOF

Call the same way as the alias:

curltime wordpress.org

Make a Windows shortcut (aka BAT file)

Put this command in CURLTIME.BAT (in the same folder as curl.exe)

curl -w "@%~dp0curl-format.txt" -o NUL -s %*

Then you can simply call...

curltime wordpress.org

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

You need to have the file /root/test/devenv/openstack-rhel/pom.xml

This file need to have the followings elements:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.openstack</groupId>
    <artifactId>openstack-rhel-rpms</artifactId>
    <version>2012.1-SNAPSHOT</version>
    <packaging>pom</packaging>
</project>

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

This appears to be a problem with the way mac is handling reading the /etc/hosts file. See for example http://youtrack.jetbrains.com/issue/IDEA-96865

Adding the hostname to the hosts file as bond described should not be required, but it does solve the problem.

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

Redirect pages in JSP?

Hello there: If you need more control on where the link should redirect to, you could use this solution.

Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.

You could use JSTL core LIKE:

<!--include the library-->
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%--create a var to store link--%>
<core:set var="linkToRedirect">
  <%--test the condition you need--%>
  <core:choose>
    <core:when test="${USER IS REGISTER}">
      checkout.jsp
    </core:when>
    <core:otherwise>
      registration.jsp
    </core:otherwise>
  </core:choose>
</core:set>

EXPLAINING: is the same as...

 //pseudo code
 if(condition == true)
   set linkToRedirect = checkout.jsp
 else
   set linkToRedirect = registration.jsp

THEN: in simple HTML...

<a href="your.domain.com/${linkToRedirect}">CHECKOUT</a>

Array Index Out of Bounds Exception (Java)

This is Very Good Example of minus Length of an array in java, i am giving here both examples

 public static int linearSearchArray(){

   int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
   int key = 7;
   int i = 0;
   int count = 0;
   for ( i = 0; i< arrayOFInt.length; i++){
        if ( arrayOFInt[i]  == key ){
         System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
         count ++;
        }
   }

   System.out.println("this Element found the ("+ count +") number of Times");
return i;  
}

this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.

How to extract a string between two delimiters

If you have just a pair of brackets ( [] ) in your string, you can use indexOf():

String str = "ABC[ This is the text to be extracted ]";    
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

How to redirect page after click on Ok button on sweet alert?

To specify a callback function, you have to use an object as the first argument, and the callback function as the second argument.

echo '<script>
    setTimeout(function() {
        swal({
            title: "Wow!",
            text: "Message!",
            type: "success"
        }, function() {
            window.location = "redirectURL";
        });
    }, 1000);
</script>';

Is it possible to include one CSS file in another?

@import url('style.css');

As opposed to the best answer, it is not recommended to aggregate all CSS files into one chunk when using HTTP/2.0

How to search a Git repository by commit message?

git log --grep=<pattern>
            Limit the commits output to ones with log message that matches the
            specified pattern (regular expression).

How do I get the fragment identifier (value after hash #) from a URL?

No need for jQuery

var type = window.location.hash.substr(1);

vertical-align: middle doesn't work

The answer given by Matt K works perfectly fine.

However it is important to note one thing - If the div you are applying it to has absolute positioning, it wont work. For it to work, do this -

<div style="position:absolute; hei...">
   <div style="position:relative; display: table-cell; vertical-align:middle; hei..."> 
      <!-- here position MUST be relative, this div acts as a wrapper-->
      ...
   </div>
</div>

Best way to "negate" an instanceof

I don't know what you imagine when you say "beautiful", but what about this? I personally think it's worse than the classic form you posted, but somebody might like it...

if (str instanceof String == false) { /* ... */ }

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

jquery $(window).height() is returning the document height

I had the same problem, and using this solved it.

var w = window.innerWidth;
var h = window.innerHeight;

How to get the latest file in a folder?

I would suggest using glob.iglob() instead of the glob.glob(), as it is more efficient.

glob.iglob() Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

Which means glob.iglob() will be more efficient.

I mostly use below code to find the latest file matching to my pattern:

LatestFile = max(glob.iglob(fileNamePattern),key=os.path.getctime)


NOTE: There are variants of max function, In case of finding the latest file we will be using below variant: max(iterable, *[, key, default])

which needs iterable so your first parameter should be iterable. In case of finding max of nums we can use beow variant : max (num1, num2, num3, *args[, key])

Handling errors in Promise.all

Not the best way to error log, but you can always set everything to an array for the promiseAll, and store the resulting results into new variables.

If you use graphQL you need to postprocess the response regardless and if it doesn't find the correct reference it'll crash the app, narrowing down where the problem is at

const results = await Promise.all([
  this.props.client.query({
    query: GET_SPECIAL_DATES,
  }),
  this.props.client.query({
    query: GET_SPECIAL_DATE_TYPES,
  }),
  this.props.client.query({
    query: GET_ORDER_DATES,
  }),
]).catch(e=>console.log(e,"error"));
const specialDates = results[0].data.specialDates;
const specialDateTypes = results[1].data.specialDateTypes;
const orderDates = results[2].data.orders;

Sql Server return the value of identity column after insert statement

send an output parameter like

@newId int output

at the end use

    select @newId = Scope_Identity() 

     return @newId 

Generate an integer sequence in MySQL

The simplest way to do this is:

SET @seq := 0;
SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
FROM your_table yt;

or in one query:

SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
FROM (SELECT @seq := 0) s, your_table yt;

The FLOOR() function is used here to get an INTEGER in place of a FLOAT. Sometimes it is needed.

My answer was inspired by David Poor answer. Thanks David!

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

Converting from byte to int in java

byte b = (byte)0xC8;
int v1 = b;       // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)

Most of the time v2 is the way you really need.

Convert line endings

Doing this with POSIX is tricky:

  • POSIX Sed does not support \r or \15. Even if it did, the in place option -i is not POSIX

  • POSIX Awk does support \r and \15, however the -i inplace option is not POSIX

  • d2u and dos2unix are not POSIX utilities, but ex is

  • POSIX ex does not support \r, \15, \n or \12

To remove carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file

To add carriage returns:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file

CSS Margin: 0 is not setting to 0

I just started learning CSS today and encountered the same problem and I think You don't need to reset style of all HTML tags. You need to reset default margin of top HTML You used, which is paragraph tag. And I know this is old question, but maybe my solution below will help somebody.

Try this:

body{   
    margin: 0; 
    background:#F0F0F0;
}
p{
    margin: 0;
}

How can I implement rate limiting with Apache? (requests per second)

In Apache 2.4, there's a new stock module called mod_ratelimit. For emulating modem speeds, you can use mod_dialup. Though I don't see why you just couldn't use mod_ratelimit for everything.

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

Working with a List of Lists in Java

Something like this would work for reading:

String filename = "something.csv";
BufferedReader input = null;
List<List<String>> csvData = new ArrayList<List<String>>();
try 
{
    input =  new BufferedReader(new FileReader(filename));
    String line = null;
    while (( line = input.readLine()) != null)
    {
        String[] data = line.split(",");
        csvData.add(Arrays.toList(data));
    }
}
catch (Exception ex)
{
      ex.printStackTrace();
}
finally 
{
    if(input != null)
    {
        input.close();
    }
}

Mongod complains that there is no /data/db folder

MongoDB can be confusing regarding the dbPath folder.

When you run mongod without dbpath then the default path is /data/db

However when you start it as a service, e.g. systemctl start mongod then it reads on configuration file, typially /etc/mongod.cfg and in this config file the defaults are

Platform Package Manager Default storage.dbPath
RHEL / CentOS and Amazon yum /var/lib/mongo
SUSE zypper /var/lib/mongo
Ubuntu and Debian apt /var/lib/mongodb
macOS brew /usr/local/var/mongodb

So, by accident your MongoDB tries to access different data folders depending on how you start the service.

C# Parsing JSON array of objects

Though this is an old question, I thought I'd post my answer anyway, if that helps someone in future

 JArray array = JArray.Parse(jsonString);
 foreach (JObject obj in array.Children<JObject>())
 {
     foreach (JProperty singleProp in obj.Properties())
     {
         string name = singleProp.Name;
         string value = singleProp.Value.ToString();
         //Do something with name and value
         //System.Windows.MessageBox.Show("name is "+name+" and value is "+value);
      }
 }

This solution uses Newtonsoft library, don't forget to include using Newtonsoft.Json.Linq;

Where can I read the Console output in Visual Studio 2015

You should use Console.ReadLine() if you want to read some input from the console.

To see your code running in Console:

In Solution Explorer (View - Solution Explorer from the menu), right click on your project, select Open Folder in File Explorer, to find where your project path is.

Supposedly the path is C:\code\myProj .

Open the Command Prompt app in Windows.

Change to your folder path. cd C:\code\myProj

Change to the debug folder, where you should find your program executable. cd bin\debug

Run your program executable, it should end in .exe extension.

Example:

myproj.exe

You should see what you output in Console.Out.WriteLine() .

Identify duplicates in a List

java 8 base solution:

List duplicates =    
list.stream().collect(Collectors.groupingBy(Function.identity()))
    .entrySet()
    .stream()
    .filter(e -> e.getValue().size() > 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

How do I get Month and Date of JavaScript in 2 digit format?

new Date().getMonth() method returns the month as a number (0-11)

You can get easily correct month number with this function.

function monthFormatted() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}

Generic type conversion FROM string

Yet another variation. Handles Nullables, as well as situations where the string is null and T is not nullable.

public class TypedProperty<T> : Property where T : IConvertible
{
    public T TypedValue
    {
        get
        {
            if (base.Value == null) return default(T);
            var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
            return (T)Convert.ChangeType(base.Value, type);
        }
        set { base.Value = value.ToString(); }
    }
}

[Vue warn]: Property or method is not defined on the instance but referenced during render

If you use two times vue instance. Then it will give you this error. For example in app.js and your own script tag in view file. Just use one time

 const app = new Vue({
    el: '#app',
});

Vertical Align text in a Label

I had a similar problem and solved it wrapping the label into a div and setting the following styles:

<div style="display: table; vertical-align: middle">
  <label style="display: table-cell;" ... > ... </label>
</div>

Live Video Streaming with PHP

For live video conferencing you can't ignore the need of a streaming server.

Yes, flash will let you display video from a webcam within the local flash control, but that won't let you then send that video over the network - for that you need a streaming server to send it to.

If you're going to build something like this it's prudent to think about how you're going to host the video from a very early stage as it will influence how you build the application. Flash/Flex/Silverlight/Windows Media....etc....

RequiredIf Conditional Validation Attribute

I had the same problem yesterday, but I did it in a very clean way which works for both client side and server side validation.

Condition: Based on the value of other property in the model, you want to make another property required. Here is the code:

public class RequiredIfAttribute : RequiredAttribute
{
  private String PropertyName { get; set; }
  private Object DesiredValue { get; set; }

  public RequiredIfAttribute(String propertyName, Object desiredvalue)
  {
    PropertyName = propertyName;
    DesiredValue = desiredvalue;
  }

  protected override ValidationResult IsValid(object value, ValidationContext context)
  {
    Object instance = context.ObjectInstance;
    Type type = instance.GetType();
    Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
    if (proprtyvalue.ToString() == DesiredValue.ToString())
    {
      ValidationResult result = base.IsValid(value, context);
      return result;
    }
    return ValidationResult.Success;
  }
}

PropertyName is the property on which you want to make your condition
DesiredValue is the particular value of the PropertyName (property) for which your other property has to be validated for required

Say you have the following:

public enum UserType
{
  Admin,
  Regular
}

public class User
{
  public UserType UserType {get;set;}

  [RequiredIf("UserType",UserType.Admin,
              ErrorMessageResourceName="PasswordRequired", 
              ErrorMessageResourceType = typeof(ResourceString))]
  public string Password { get; set; }
}

At last but not the least, register adapter for your attribute so that it can do client side validation (I put it in global.asax, Application_Start)

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),
                                                      typeof(RequiredAttributeAdapter));

EDITED

Some people was complaining that the client side fires no matter what or it does not work. So I modified the above code to do conditional client side validation with Javascript as well. For this case you don't need to register adapter

 public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
    {
        private String PropertyName { get; set; }
        private Object DesiredValue { get; set; }
        private readonly RequiredAttribute _innerAttribute;

        public RequiredIfAttribute(String propertyName, Object desiredvalue)
        {
            PropertyName = propertyName;
            DesiredValue = desiredvalue;
            _innerAttribute = new RequiredAttribute();
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

            if (dependentValue.ToString() == DesiredValue.ToString())
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
                }
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "requiredif",
            };
            rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
            rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;

            yield return rule;
        }
    }

And finally the javascript ( bundle it and renderit...put it in its own script file)

$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options) {
    options.rules['requiredif'] = options.params;
    options.messages['requiredif'] = options.message;
});

$.validator.addMethod('requiredif', function (value, element, parameters) {
    var desiredvalue = parameters.desiredvalue;
    desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
    var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
    var actualvalue = {}
    if (controlType == "checkbox" || controlType == "radio") {
        var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
        actualvalue = control.val();
    } else {
        actualvalue = $("#" + parameters.dependentproperty).val();
    }
    if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
        var isValid = $.validator.methods.required.call(this, value, element, parameters);
        return isValid;
    }
    return true;
});

You need obviously the unobstrusive validate jQuery to be included as requirement

Using print statements only to debug

The logging module has everything you could want. It may seem excessive at first, but only use the parts you need. I'd recommend using logging.basicConfig to toggle the logging level to stderr and the simple log methods, debug, info, warning, error and critical.

import logging, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
logging.debug('A debug message!')
logging.info('We processed %d records', len(processed_records))

Java Thread Example?

There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.

HTML-encoding lost when attribute read from input field

Prototype has it built-in the String class. So if you are using/plan to use Prototype, it does something like:

'<div class="article">This is an article</div>'.escapeHTML();
// -> "&lt;div class="article"&gt;This is an article&lt;/div&gt;"

Interface defining a constructor signature?

Late, but for someone need.

You can using Func<TResult>

void Create(Func<IDrawable> func)
{
  IDrawable result = func.Invoke();
}

GraphicsDeviceManager graphicsDeviceManager =...;
xxx.Create(() => new Draw(graphicsDeviceManager));
yyy.Create(() => new Update(graphicsDeviceManager));

Including a groovy script in another groovy

Another way to do this is to define the functions in a groovy class and parse and add the file to the classpath at runtime:

File sourceFile = new File("path_to_file.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

This error is because of multiple project having the offending resources.

Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)

enter image description here

How to integrate SAP Crystal Reports in Visual Studio 2017

Extracted from official SAP site https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads.

Item # 3 fixed my installation.

This applies for ANY Patch after SP 21

  1. FlexNet and In-Place Upgrade does not work: Once user receive the update notification from FlexNet server and finish SP21 upgrade, the product will NOT work. User MUST repair CR4VS and CRRuntime64 in Control Panel\Programs. That’s a by design change to installer.

    a. Please notice that we are still facing problems on configuring FlexNet upgrade server, so currently user will NOT receive SP21 notification

  2. Microsoft Windows Update KB2999226 is a prerequisite for SP21.

    a. This is same as BI 4.2 SP4 and BI 4.1 SP10. Please refer to SAP Note 2451830.

  3. For VS2017 integration, user needs use “run as Administrator” by right-clicking setup.exe, even if you are already log on by using Administrator account

  4. As most of CR/RAS .NET Assemblies are now re-versioned from 13.0.2000.0 to 13.0.3500.0, user MUST remove all old CR assemblies from Reference list and add the new version of CR assemblies, then rebuild the application.

    a. For those customer/user who do not wanted to rebuilt their application, there’s workaround to use in app.config/web.config, please see attachment.

WinFormCRViewer.zip

  1. For reports using the ADO.Net DB connection, in previous SP's, you could only work under .Net Framework 2.0/3.5, so using in app.config is required. Now in SP21, ADO.Net is only supported on .Net Framework 3.5 or above.

'gulp' is not recognized as an internal or external command

I solved the problem by uninstalling NodeJs and gulp then re-installing both again.

To install gulp globally I executed the following command

npm install -g gulp

Iterating through struct fieldnames in MATLAB

Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.

fns{i}
teststruct.(fns{i})

Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.

name_as_char = 'a'
name_as_cellstr = {'a'}

React-Router open Link in new tab

Starting with react_router 1.0, the props will be passed onto the anchor tag. You can directly use target="_blank". Discussed here: https://github.com/ReactTraining/react-router/issues/2188

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

It is important that the Main method is placed in the class that is properly configured in Visual Studio as a start-up object:

  • Right-click your project in project explorer; choose "Properties..."
  • In the properties dialog, choose "Application" tab
  • In the application tab, choose SimpleAIMLEditor.Program from the drop-down for your start-up object

Now run your application again. The error will disappear.

Is there a way to access an iteration-counter in Java's for-each loop?

Using lambdas and functional interfaces in Java 8 makes creating new loop abstractions possible. I can loop over a collection with the index and the collection size:

List<String> strings = Arrays.asList("one", "two","three","four");
forEach(strings, (x, i, n) -> System.out.println("" + (i+1) + "/"+n+": " + x));

Which outputs:

1/4: one
2/4: two
3/4: three
4/4: four

Which I implemented as:

   @FunctionalInterface
   public interface LoopWithIndexAndSizeConsumer<T> {
       void accept(T t, int i, int n);
   }
   public static <T> void forEach(Collection<T> collection,
                                  LoopWithIndexAndSizeConsumer<T> consumer) {
      int index = 0;
      for (T object : collection){
         consumer.accept(object, index++, collection.size());
      }
   }

The possibilities are endless. For example, I create an abstraction that uses a special function just for the first element:

forEachHeadTail(strings, 
                (head) -> System.out.print(head), 
                (tail) -> System.out.print(","+tail));

Which prints a comma separated list correctly:

one,two,three,four

Which I implemented as:

public static <T> void forEachHeadTail(Collection<T> collection, 
                                       Consumer<T> headFunc, 
                                       Consumer<T> tailFunc) {
   int index = 0;
   for (T object : collection){
      if (index++ == 0){
         headFunc.accept(object);
      }
      else{
         tailFunc.accept(object);
      }
   }
}

Libraries will begin to pop up to do these sorts of things, or you can roll your own.

Center text in table cell

I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:

.ui-helper-center {
    text-align: center;
}

And then add the ui-helper-center class to the table cells for which you wish to control the alignment:

<td class="ui-helper-center">Content</td>

EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.

See Gabe's answer for how to include the CSS rule into your page.

How to change colors of a Drawable in Android?

You should do this for all APIs:

Drawable myIcon = getResources().getDrawable( R.drawable.button ); 
ColorFilter filter = new LightingColorFilter( Color.BLACK, Color.BLACK);
myIcon.setColorFilter(filter);

How to put a tooltip on a user-defined function

I know you've accepted an answer for this, but there's now a solution that lets you get an intellisense style completion box pop up like for the other excel functions, via an Excel-DNA add in, or by registering an intellisense server inside your own add in. See here.

Now, i prefer the C# way of doing it - it's much simpler, as inside Excel-DNA, any class that implements IExcelAddin is picked up by the addin framework and has AutoOpen() and AutoClose() run when you open/close the add in. So you just need this:

namespace MyNameSpace {
    public class Intellisense : IExcelAddIn {
        public void AutoClose() {
        }
        public void AutoOpen() {
            IntelliSenseServer.Register();
        }
    }
}

and then (and this is just taken from the github page), you just need to use the ExcelDNA annotations on your functions:

[ExcelFunction(Description = "A useful test function that adds two numbers, and returns the sum.")]
public static double AddThem(
    [ExcelArgument(Name = "Augend", Description = "is the first number, to which will be added")] 
    double v1,
    [ExcelArgument(Name = "Addend", Description = "is the second number that will be added")]     
    double v2)
{
    return v1 + v2;
}

which are annotated using the ExcelDNA annotations, the intellisense server will pick up the argument names and descriptions.

enter image description here enter image description here

There are examples for using it with just VBA too, but i'm not too into my VBA, so i don't use those parts.

How to use comparison and ' if not' in python?

You can do:

if not (u0 <= u <= u0+step):
    u0 = u0+ step # change the condition until it is satisfied
else:
    do sth. # condition is satisfied

Using a loop:

while not (u0 <= u <= u0+step):
   u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied

display Java.util.Date in a specific format

It makes no sense, but:

System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))

SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String

How to check if running as root in a bash script

id -u is much better than whoami, since some systems like android may not provide the word root.

Example:

# whoami
whoami
whoami: unknown uid 0

Largest and smallest number in an array

using System;

namespace greatest
{

    class Greatest
    {
        public static void Main(String[] args)
        {   
            //get the number of elements
            Console.WriteLine("enter the number of elements");
            int i;
            i=Convert.ToInt32(Console.ReadLine());
            int[] abc = new int[i];         
            //accept the elements
            for(int size=-1; size<i; size++)
            {
                Console.WriteLine("enter the elements");
                abc[size]=Convert.ToInt32(Console.ReadLine());
            }
            //Greatest
            int max=abc.Max();
            int min=abc.Min();
            Console.WriteLine("the m", max);
            Console.WriteLine("the mi", min);

            Console.Read();
        }
    }
}

Is there a way to remove the separator line from a UITableView?

In Swift:

tableView.separatorStyle = .None

How to lowercase a pandas dataframe string column if it has missing values?

copy your Dataframe column and simply apply

df=data['x']
newdf=df.str.lower()

reCAPTCHA ERROR: Invalid domain for site key

I had the same problems I solved it. I went to https://www.google.com/recaptcha/admin and clicked on the domain and then went to key settings at the bottom.

There I disabled the the option below Domain Name Validation Verify the origin of reCAPTCHA solution

clicked on save and captcha started working.

I think this has to do with way the server is setup. I am on a shared hosting and just was transferred without notice from Liquidweb to Deluxehosting(as the former sold their share hosting to the latter) and have been having such problems with many issues. I think in this case google is checking the server but it is identifying as shared server name and not my domain. When i uncheck the "verify origin" it starts working. Hope this helps solve the problem for the time being.

AttributeError: 'dict' object has no attribute 'predictors'

The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

For Swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

For Swift 4

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 @objc func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

I'm sure it'd turn into more than 10 lines of code, but have you considered a form based app where pressing the buttons does things like changing the colour of the background or changes the size of the text? This would show them how interactive programs work. It would also show them that they, as programmer, are in complete control of what the computer (program) does.

Hopefully it would lead them to make suggestions for other things they could change and then onto other things they might want to do.

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

SELECT date1 - date2
  FROM some_table

returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So

SELECT (date1 - date2) * 24 * 60 difference_in_minutes
  FROM some_table

should be what you're looking for

Good examples of python-memcache (memcached) being used in Python?

I would advise you to use pylibmc instead.

It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.

And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.

How to check if a table contains an element in Lua?

Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true as the value. +1 to interjay.

unexpected T_VARIABLE, expecting T_FUNCTION

You can not put

$connection = sqlite_open("[path]/data/users.sqlite", 0666);

outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.

Check if a folder exist in a directory and create them using C#

This should work

if(!Directory.Exists(@"C:\MP_Upload")) {
    Directory.CreateDirectory(@"C:\MP_Upload");
}

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

System.currentTimeMillis vs System.nanoTime

System.nanoTime() isn't supported in older JVMs. If that is a concern, stick with currentTimeMillis

Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms). I'm not sure why, but some Windows machines are just as accurate as Linux machines.

I have used GAGETimer in the past with moderate success.

Dynamically load JS inside JS

To author my plugin I needed to load external scripts and styles inside a JS file, all of which were predefined. To achieve this, I did the following:

    this.loadRequiredFiles = function (callback) {
        var scripts = ['xx.js', 'yy.js'];
        var styles = ['zz.css'];
        var filesloaded = 0;
        var filestoload = scripts.length + styles.length;
        for (var i = 0; i < scripts.length; i++) {
            log('Loading script ' + scripts[i]);
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = scripts[i];
            script.onload = function () {
                log('Loaded script');
                log(this);
                filesloaded++;  // (This means increment, i.e. add one)
                finishLoad();
            };
            document.head.appendChild(script);
        }
        for (var i = 0; i < styles.length; i++) {
            log('Loading style ' + styles[i]);
            var style = document.createElement('link');
            style.rel = 'stylesheet';
            style.href = styles[i];
            style.type = 'text/css';
            style.onload = function () {
                log('Loaded style');
                log(this);
                filesloaded++;
                finishLoad();
            };
            document.head.appendChild(style);
        }
        function finishLoad() {
            if (filesloaded === filestoload) {
                callback();
            }
        }
    };

More of the script in context:

function myPlugin() {

    var opts = {
        verbose: false
    };                          ///< The options required to run this function
    var self = this;            ///< An alias to 'this' in case we're in jQuery                         ///< Constants required for this function to work

    this.getOptions = function() {
        return opts;
    };

    this.setOptions = function(options) {
        for (var x in options) {
            opts[x] = options[x];
        }
    };

    /**
     * @brief Load the required files for this plugin
     * @param {Function} callback A callback function to run when all files have been loaded
     */
    this.loadRequiredFiles = function (callback) {
        var scripts = ['xx.js', 'yy.js'];
        var styles = ['zz.css'];
        var filesloaded = 0;
        var filestoload = scripts.length + styles.length;
        for (var i = 0; i < scripts.length; i++) {
            log('Loading script ' + scripts[i]);
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = scripts[i];
            script.onload = function () {
                log('Loaded script');
                log(this);
                filesloaded++;
                finishLoad();
            };
            document.head.appendChild(script);
        }
        for (var i = 0; i < styles.length; i++) {
            log('Loading style ' + styles[i]);
            var style = document.createElement('link');
            style.rel = 'stylesheet';
            style.href = styles[i];
            style.type = 'text/css';
            style.onload = function () {
                log('Loaded style');
                log(this);
                filesloaded++;
                finishLoad();
            };
            document.head.appendChild(style);
        }
        function finishLoad() {
            if (filesloaded === filestoload) {
                callback();
            }
        }
    };

    /**
     * @brief Enable user-controlled logging within this function
     * @param {String} msg The message to log
     * @param {Boolean} force True to log message even if user has set logging to false
     */
    function log(msg, force) {
        if (opts.verbose || force) {
            console.log(msg);
        }
    }

    /**
     * @brief Initialise this function
     */
    this.init = function() {
        self.loadRequiredFiles(self.afterLoadRequiredFiles);
    };

    this.afterLoadRequiredFiles = function () {
        // Do stuff
    };

}

Error when using scp command "bash: scp: command not found"

Issue is with remote server, can you login to the remote server and check if "scp" works

probable causes: - scp is not in path - openssh client not installed correctly

for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/

How to put comments in Django templates

Multiline comment in django templates use as follows ex: for .html etc.

{% comment %} All inside this tags are treated as comment {% endcomment %}

operator << must take exactly one argument

The problem is that you define it inside the class, which

a) means the second argument is implicit (this) and

b) it will not do what you want it do, namely extend std::ostream.

You have to define it as a free function:

class A { /* ... */ };
std::ostream& operator<<(std::ostream&, const A& a);

Saving images in Python at a very high quality

In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:

Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:

import seaborn as sb

image = sb.heatmap(matrix)   # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png")   # This saves it

This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.

Another way I like is this. I set the size of the next image as follows:

plt.subplots(figsize=(15,15))

And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)

What is the difference between up-casting and down-casting with respect to class variable

1.- Upcasting.

Doing an upcasting, you define a tag of some type, that points to an object of a subtype (Type and subtype may be called class and subclass, if you feel more comfortable...).

Animal animalCat = new Cat();

What means that such tag, animalCat, will have the functionality (the methods) of type Animal only, because we've declared it as type Animal, not as type Cat.

We are allowed to do that in a "natural/implicit/automatic" way, at compile-time or at a run-time, mainly because Cat inherits some of its functionality from Animal; for example, move(). (At least, cat is an animal, isn't it?)

2.- Downcasting.

But, what would happen if we need to get the functionality of Cat, from our type Animal tag?.

As we have created the animalCat tag pointing to a Cat object, we need a way to call the Cat object methods, from our animalCat tag in a some smart pretty way.

Such procedure is what we call Downcasting, and we can do it only at the run-time.

Time for some code:

public class Animal {
    public String move() {
        return "Going to somewhere";
    }
}

public class Cat extends Animal{
    public String makeNoise() {
        return "Meow!";
    }   
}

public class Test {

    public static void main(String[] args) {
        
    //1.- Upcasting 
    //  __Type_____tag________object
        Animal animalCat = new Cat();
    //Some animal movement
        System.out.println(animalCat.move());
        //prints "Going to somewhere"
        
    //2.- Downcasting   
    //Now you wanna make some Animal noise.
        //First of all: type Animal hasn't any makeNoise() functionality.
        //But Cat can do it!. I wanna be an Animal Cat now!!
        
        //___________________Downcast__tag_____ Cat's method
        String animalNoise = ( (Cat) animalCat ).makeNoise();
        
        System.out.println(animalNoise);
        //Prints "Meow!", as cats usually done.
        
    //3.- An Animal may be a Cat, but a Dog or a Rhinoceros too.
        //All of them have their own noises and own functionalities.
        //Uncomment below and read the error in the console:
        
    //  __Type_____tag________object
        //Cat catAnimal = new Animal();
        
    }

}

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Start by adding a regular matInput to your template. Let's assume you're using the formControl directive from ReactiveFormsModule to track the value of the input.

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms.

import { FormsModule, ReactiveFormsModule } from "@angular/forms"; //this to use ngModule

...

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    FormsModule,
    RouterModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MaterialModule],

Fetch: POST json data

Had the same issue - no body was sent from a client to a server.

Adding Content-Type header solved it for me:

var headers = new Headers();

headers.append('Accept', 'application/json'); // This one is enough for GET requests
headers.append('Content-Type', 'application/json'); // This one sends body

return fetch('/some/endpoint', {
    method: 'POST',
    mode: 'same-origin',
    credentials: 'include',
    redirect: 'follow',
    headers: headers,
    body: JSON.stringify({
        name: 'John',
        surname: 'Doe'
    }),
}).then(resp => {
    ...
}).catch(err => {
   ...
})

Having services in React application

Keep in mind that the purpose of React is to better couple things that logically should be coupled. If you're designing a complicated "validate password" method, where should it be coupled?

Well you're going to need to use it every time the user needs to input a new password. This could be on the registration screen, a "forgot password" screen, an administrator "reset password for another user" screen, etc.

But in any of those cases, it's always going to be tied to some text input field. So that's where it should be coupled.

Make a very small React component that consists solely of an input field and the associated validation logic. Input that component within all of the forms that might want to have a password input.

It's essentially the same outcome as having a service/factory for the logic, but you're coupling it directly to the input. So you now never need to tell that function where to look for it's validation input, as it is permanently tied together.

How to make use of SQL (Oracle) to count the size of a string?

Regardless to Your example

select length('Burger') from dual;

I hope this will help :)

No value accessor for form control with name: 'recipient'

Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule

Function to calculate distance between two coordinates

I have written the function to find distance between two coordinates. It will return distance in meter.

 function findDistance() {
   var R = 6371e3; // R is earth’s radius
   var lat1 = 23.18489670753479; // starting point lat
   var lat2 = 32.726601;         // ending point lat
   var lon1 = 72.62524545192719; // starting point lon
   var lon2 = 74.857025;         // ending point lon
   var lat1radians = toRadians(lat1);
   var lat2radians = toRadians(lat2);

   var latRadians = toRadians(lat2-lat1);
   var lonRadians = toRadians(lon2-lon1);

   var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
        Math.cos(lat1radians) * Math.cos(lat2radians) *
        Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

   var d = R * c;

   console.log(d)
}

function toRadians(val){
    var PI = 3.1415926535;
    return val / 180.0 * PI;
}

Selecting data from two different servers in SQL Server

These are all fine answers, but this one is missing and it has it's own powerful uses. Possibly it doesn't fit what the OP wanted, but the question was vague and I feel others may find their way here. Basically you can use 1 window to simultaneously run a query against multiple servers, here's how:

In SSMS open Registered Servers and create a New Server Group under Local Server Groups.

Under this group create New Server Registration for each server you wish to query. If the DB names are different ensure to set a default for each in the properties.

Now go back to the Group you created in the first step, right click and select New Query. A new query window will open and any query you run will be executed on each server in the group. The results are presented in a single data set with an extra column name indicating which server the record came from. If you use the status bar you will note the server name is replaced with multiple.

Python Serial: How to use the read or readline function to read more than 1 character at a time

I was reciving some date from my arduino uno (0-1023 numbers). Using code from 1337holiday, jwygralak67 and some tips from other sources:

import serial
import time

ser = serial.Serial(
    port='COM4',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
seq = []
count = 1

while True:
    for c in ser.read():
        seq.append(chr(c)) #convert from ANSII
        joined_seq = ''.join(str(v) for v in seq) #Make a string from array

        if chr(c) == '\n':
            print("Line " + str(count) + ': ' + joined_seq)
            seq = []
            count += 1
            break


ser.close()

How to get annotations of a member variable?

package be.fery.annotation;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;

@Entity
public class User {
    @Id
    private Long id;

    @Column(name = "ADDRESS_ID")
    private Address address;

    @PrePersist
    public void doStuff(){

    }
}

And a testing class:

    package be.fery.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AnnotationIntrospector {

    public AnnotationIntrospector() {
        super();
    }

    public Annotation[] findClassAnnotation(Class<?> clazz) {
        return clazz.getAnnotations();
    }

    public Annotation[] findMethodAnnotation(Class<?> clazz, String methodName) {

        Annotation[] annotations = null;
        try {
            Class<?>[] params = null;
            Method method = clazz.getDeclaredMethod(methodName, params);
            if (method != null) {
                annotations = method.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    public Annotation[] findFieldAnnotation(Class<?> clazz, String fieldName) {
        Annotation[] annotations = null;
        try {
            Field field = clazz.getDeclaredField(fieldName);
            if (field != null) {
                annotations = field.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        AnnotationIntrospector ai = new AnnotationIntrospector();
        Annotation[] annotations;
        Class<User> userClass = User.class;
        String methodDoStuff = "doStuff";
        String fieldId = "id";
        String fieldAddress = "address";

        // Find class annotations
        annotations = ai.findClassAnnotation(be.fery.annotation.User.class);
        System.out.println("Annotation on class '" + userClass.getName()
                + "' are:");
        showAnnotations(annotations);

        // Find method annotations
        annotations = ai.findMethodAnnotation(User.class, methodDoStuff);
        System.out.println("Annotation on method '" + methodDoStuff + "' are:");
        showAnnotations(annotations);

        // Find field annotations
        annotations = ai.findFieldAnnotation(User.class, fieldId);
        System.out.println("Annotation on field '" + fieldId + "' are:");
        showAnnotations(annotations);

        annotations = ai.findFieldAnnotation(User.class, fieldAddress);
        System.out.println("Annotation on field '" + fieldAddress + "' are:");
        showAnnotations(annotations);

    }

    public static void showAnnotations(Annotation[] ann) {
        if (ann == null)
            return;
        for (Annotation a : ann) {
            System.out.println(a.toString());
        }
    }

}

Hope it helps...

;-)

How do I clone a github project to run locally?

You clone a repository with git clone [url]. Like so,

$ git clone https://github.com/libgit2/libgit2

On localhost, how do I pick a free port number?

If you only need to find a free port for later use, here is a snippet similar to a previous answer, but shorter, using socketserver:

import socketserver

with socketserver.TCPServer(("localhost", 0), None) as s:
    free_port = s.server_address[1]

Note that the port is not guaranteed to remain free, so you may need to put this snippet and the code using it in a loop.