Programs & Examples On #Transaction isolation

Transaction isolation relates to the visibility and impact of changes made in one transaction on concurrent transactions.

Any way to select without causing locking in MySQL?

Depending on your table type, locking will perform differently, but so will a SELECT count. For MyISAM tables a simple SELECT count(*) FROM table should not lock the table since it accesses meta data to pull the record count. Innodb will take longer since it has to grab the table in a snapshot to count the records, but it shouldn't cause locking.

You should at least have concurrent_insert set to 1 (default). Then, if there are no "gaps" in the data file for the table to fill, inserts will be appended to the file and SELECT and INSERTs can happen simultaneously with MyISAM tables. Note that deleting a record puts a "gap" in the data file which will attempt to be filled with future inserts and updates.

If you rarely delete records, then you can set concurrent_insert equal to 2, and inserts will always be added to the end of the data file. Then selects and inserts can happen simultaneously, but your data file will never get smaller, no matter how many records you delete (except all records).

The bottom line, if you have a lot of updates, inserts and selects on a table, you should make it InnoDB. You can freely mix table types in a system though.

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

Android Studio 3.0 below working method:
Find your old zipped project.
If you have built the apk, you'll find the password in file:

Project\.gradle\2.14.1\taskArtifacts\taskArtifacts.bin

Pandroid.injected.signing.store.password=password

If you don't have zipped project, search your git repositories if you have .gradle folder pushed or not.
Otherwise you'll have to recover files and search files by content "Pandroid.injected.signing.store.password".

React this.setState is not a function

use arrow functions, as arrow functions point to parent scope and this will be available. (substitute of bind technique)

Where does the .gitignore file belong?

Also, if you create a new account on Github you will have the option to add .gitignore and it will be setup automatically on the right/standard location of your working place. You don't have to add anything in there at the begin, just alter the contents any time you want.

Navigation Controller Push View Controller

-  (void) loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                error:(NSError *)error{
    UINavigationController *nav = [self.storyboard instantiateViewControllerWithIdentifier:@"nav"];
    ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"LoggedInVC"];
    [nav pushViewController:vc animated:YES];
    [self presentViewController:nav animated:YES completion:nil];
}

"nav" is the Storyboard ID for my navigation controller "vc" is the Storyboard ID for my first view controller connected to my navigation controller

-hope this helps

How do I detect "shift+enter" and generate a new line in Textarea?

I found this thread looking for a way to control Shift + any key. I pasted together other solutions to make this combined function to accomplish what I needed. I hope it helps someone else.

function () {
    return this.each(function () {
    $(this).keydown(function (e) {
        var key = e.charCode || e.keyCode || 0;
        // Shift + anything is not desired
        if (e.shiftKey) {
            return false;
        }
        // allow backspace, tab, delete, enter, arrows, numbers 
        //and keypad numbers ONLY
        // home, end, period, and numpad decimal
        return (
            key == 8 ||
            key == 9 ||
            key == 13 ||
            key == 46 ||
            key == 110 ||
            key == 190 ||
            (key >= 35 && key <= 40) ||
            (key >= 48 && key <= 57) ||
            (key >= 96 && key <= 105));
    });
});

How can I create a "Please Wait, Loading..." animation using jQuery?

You could do this various different ways. It could be a subtle as a small status on the page saying "Loading...", or as loud as an entire element graying out the page while the new data is loading. The approach I'm taking below will show you how to accomplish both methods.

The Setup

Let's start by getting us a nice "loading" animation from http://ajaxload.info I'll be using enter image description here

Let's create an element that we can show/hide anytime we're making an ajax request:

<div class="modal"><!-- Place at bottom of page --></div>

The CSS

Next let's give it some flair:

/* Start by setting display:none to make this hidden.
   Then we position it in relation to the viewport window
   with position:fixed. Width, height, top and left speak
   for themselves. Background we set to 80% white with
   our animation centered, and no-repeating */
.modal {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 ) 
                url('http://i.stack.imgur.com/FhHRx.gif') 
                50% 50% 
                no-repeat;
}

/* When the body has the loading class, we turn
   the scrollbar off with overflow:hidden */
body.loading .modal {
    overflow: hidden;   
}

/* Anytime the body has the loading class, our
   modal element will be visible */
body.loading .modal {
    display: block;
}

And finally, the jQuery

Alright, on to the jQuery. This next part is actually really simple:

$body = $("body");

$(document).on({
    ajaxStart: function() { $body.addClass("loading");    },
     ajaxStop: function() { $body.removeClass("loading"); }    
});

That's it! We're attaching some events to the body element anytime the ajaxStart or ajaxStop events are fired. When an ajax event starts, we add the "loading" class to the body. and when events are done, we remove the "loading" class from the body.

See it in action: http://jsfiddle.net/VpDUG/4952/

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

READ THIS IF YOU USE Crashlytics AND ARE HAVING THIS ISSUE...

I was having the same issue as above Command /bin/sh failed with exit code 1 more specifically [31merror: Could not fetch upload-symbols settings: An unknown error occurred fetching settings.[0m

The first solution (enabling the run script only when installing) allowed me to build my target in the simulator, but I could not archive my build.

I solved this Archive issue by enabling Crashlytics on firebase. I am still used to Fabric where Crashlytics is automatically enabled. Once I enabled Crashlytics in the firebase console for the corresponding GoogleService-Info.plist I was able to Archive without this error.

How can I easily switch between PHP versions on Mac OSX?

Example: Let us switch from php 7.4 to 7.3

brew unlink [email protected]
brew install [email protected]
brew link [email protected]

If you get Warning: [email protected] is keg-only and must be linked with --force Then try with:

brew link [email protected] --force

Dynamic function name in javascript?

In recent engines, you can do

_x000D_
_x000D_
function nameFunction(name, body) {_x000D_
  return {[name](...args) {return body(...args)}}[name]_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
const x = nameFunction("wonderful function", (p) => p*2)_x000D_
console.log(x(9)) // => 18_x000D_
console.log(x.name) // => "wonderful function"
_x000D_
_x000D_
_x000D_

How to set response header in JAX-RS so that user sees download popup for Excel?

I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.

package local.test.servlet;

import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;

@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        try {

            URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
            //   /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
            System.out.println(templateFileUrl.getPath());
            String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
            String outputFileDir = "MasatoExcelHorizontalOutput";

            ReportProcessor reportProcessor = new ReportProcessor();
            ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);

            ReportSheet outputSheet = new ReportSheet("MySheet");
            outputBook.addReportSheet(outputSheet);

            reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
            System.out.println("wtf???");
            reportProcessor.process(outputBook);


            System.out.println("done!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }

    } //end doGet()

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}//end class



class OutputStreamExporter extends ReportBookExporter {

    private HttpServletResponse response;

    public OutputStreamExporter(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public String getExtention() {
        return null;
    }

    @Override
    public String getFormatType() {
        return ExcelExporter.FORMAT_TYPE;
    }

    @Override
    public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {

        System.out.println(book.getFirstVisibleTab());
        System.out.println(book.getSheetName(0));

        //TODO write to stream
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
            book.write(response.getOutputStream());
            response.getOutputStream().close();
            System.out.println("booya!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}//end class

How to ignore deprecation warnings in Python

Pass the correct arguments? :P

On the more serious note, you can pass the argument -Wi::DeprecationWarning on the command line to the interpreter to ignore the deprecation warnings.

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

/* This Program will convert Numbers from -999,999,999 to 999,999,999 into words */

#include <vector>
#include <iostream>
#include <stdexcept>
#include <string>

using namespace std;

const std::vector<std::string> first14 = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen" };
const std::vector<std::string> prefixes = { "twen", "thir", "for", "fif", "six", "seven", "eigh", "nine" };

std::string inttostr(const int number)
{
    if (number < 0)
    {
        return "minus " + inttostr(-number);
    }
    if (number <= 14)
        return first14.at(number);
    if (number < 20)
        return prefixes.at(number - 12) + "teen";
    if (number < 100) {
        unsigned int remainder = number - (static_cast<int>(number / 10) * 10);
        return prefixes.at(number / 10 - 2) + (0 != remainder ? "ty " + inttostr(remainder) : "ty");
    }
    if (number < 1000) {
        unsigned int remainder = number - (static_cast<int>(number / 100) * 100);
        return first14.at(number / 100) + (0 != remainder ? " hundred " + inttostr(remainder) : " hundred");
    }
    if (number < 1000000) {
        unsigned int thousands = static_cast<int>(number / 1000);
        unsigned int remainder = number - (thousands * 1000);
        return inttostr(thousands) + (0 != remainder ? " thousand " + inttostr(remainder) : " thousand");
    }
    if (number < 1000000000) {
        unsigned int millions = static_cast<int>(number / 1000000);
        unsigned int remainder = number - (millions * 1000000);
        return inttostr(millions) + (0 != remainder ? " million " + inttostr(remainder) : " million");
    }
    throw std::out_of_range("inttostr() value too large");
}

int main()
{
    int num;
    cout << "Enter a number to convert it into letters : ";
    cin >> num;
    cout << endl << num << " = " << inttostr(num) << endl;
    system("pause");
    return 0;
}

How to find unused/dead code in java projects

Code coverage tools, such as Emma, Cobertura, and Clover, will instrument your code and record which parts of it gets invoked by running a suite of tests. This is very useful, and should be an integral part of your development process. It will help you identify how well your test suite covers your code.

However, this is not the same as identifying real dead code. It only identifies code that is covered (or not covered) by tests. This can give you false positives (if your tests do not cover all scenarios) as well as false negatives (if your tests access code that is actually never used in a real world scenario).

I imagine the best way to really identify dead code would be to instrument your code with a coverage tool in a live running environment and to analyse code coverage over an extended period of time.

If you are runnning in a load balanced redundant environment (and if not, why not?) then I suppose it would make sense to only instrument one instance of your application and to configure your load balancer such that a random, but small, portion of your users run on your instrumented instance. If you do this over an extended period of time (to make sure that you have covered all real world usage scenarios - such seasonal variations), you should be able to see exactly which areas of your code are accessed under real world usage and which parts are really never accessed and hence dead code.

I have never personally seen this done, and do not know how the aforementioned tools can be used to instrument and analyse code that is not being invoked through a test suite - but I am sure they can be.

Convert System.Drawing.Color to RGB and Hex Value

I'm failing to see the problem here. The code looks good to me.

The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString(), c.G.ToString(), and c.B.ToString() can't actually fail (the only way I can see them failing is with a NullReferenceException, and none of them can actually be null).

You could clean the whole thing up using the following:

private static String HexConverter(System.Drawing.Color c)
{
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

private static String RGBConverter(System.Drawing.Color c)
{
    return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}

TypeError: Image data can not convert to float

Try to use this,

   plt.imshow(numpy.real(A))
   plt.show()

instead of plt.imshow(A)

Convert XML to JSON (and back) using Javascript

I would personally recommend this tool. It is an XML to JSON converter.

It is very lightweight and is in pure JavaScript. It needs no dependencies. You can simply add the functions to your code and use it as you wish.

It also takes the XML attributes into considerations.

var xml = ‘<person id=”1234” age=”30”><name>John Doe</name></person>’;
var json = xml2json(xml); 

console.log(json); 
// prints ‘{“person”: {“id”: “1234”, “age”: “30”, “name”: “John Doe”}}’

Here's an online demo!

Subtracting time.Duration from time in Go

You can negate a time.Duration:

then := now.Add(- dur)

You can even compare a time.Duration against 0:

if dur > 0 {
    dur = - dur
}

then := now.Add(dur)

You can see a working example at http://play.golang.org/p/ml7svlL4eW

JavaScript split String with white space

str.split(' ').join('§ §').split('§');

Java HTTPS client certificate authentication

They JKS file is just a container for certificates and key pairs. In a client-side authentication scenario, the various parts of the keys will be located here:

  • The client's store will contain the client's private and public key pair. It is called a keystore.
  • The server's store will contain the client's public key. It is called a truststore.

The separation of truststore and keystore is not mandatory but recommended. They can be the same physical file.

To set the filesystem locations of the two stores, use the following system properties:

-Djavax.net.ssl.keyStore=clientsidestore.jks

and on the server:

-Djavax.net.ssl.trustStore=serversidestore.jks

To export the client's certificate (public key) to a file, so you can copy it to the server, use

keytool -export -alias MYKEY -file publicclientkey.cer -store clientsidestore.jks

To import the client's public key into the server's keystore, use (as the the poster mentioned, this has already been done by the server admins)

keytool -import -file publicclientkey.cer -store serversidestore.jks

How can I work with command line on synology?

The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.

Launch Powershell or CMD, enter ssh yourAccountName@diskstation

The first time it will cache off your certificate.

EDIT:

Further detailed explanations can be found on the synology docs page:

How to login to DSM with root permission via SSH Telnet

How to delete empty folders using windows command prompt?

for /f "usebackq" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

from: http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx

Of course I'd test it first without deleting before I do that command. Also, here's a modded version from the comments that includes folders with spaces:

 for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

P.S. there are more comments in the blog post that might help you out so be sure to read those too before you try this out

Find element's index in pandas Series

Converting to an Index, you can use get_loc

In [1]: myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])

In [3]: Index(myseries).get_loc(7)
Out[3]: 3

In [4]: Index(myseries).get_loc(10)
KeyError: 10

Duplicate handling

In [5]: Index([1,1,2,2,3,4]).get_loc(2)
Out[5]: slice(2, 4, None)

Will return a boolean array if non-contiguous returns

In [6]: Index([1,1,2,1,3,2,4]).get_loc(2)
Out[6]: array([False, False,  True, False, False,  True, False], dtype=bool)

Uses a hashtable internally, so fast

In [7]: s = Series(randint(0,10,10000))

In [9]: %timeit s[s == 5]
1000 loops, best of 3: 203 µs per loop

In [12]: i = Index(s)

In [13]: %timeit i.get_loc(5)
1000 loops, best of 3: 226 µs per loop

As Viktor points out, there is a one-time creation overhead to creating an index (its incurred when you actually DO something with the index, e.g. the is_unique)

In [2]: s = Series(randint(0,10,10000))

In [3]: %timeit Index(s)
100000 loops, best of 3: 9.6 µs per loop

In [4]: %timeit Index(s).is_unique
10000 loops, best of 3: 140 µs per loop

How to display loading message when an iFrame is loading?

$('iframe').load(function(){
      $(".loading").remove();
    alert("iframe is done loading")
}).show();


<iframe src="http://www.google.com" style="display:none;" width="600" height="300"/>
<div class="loading" style="width:600px;height:300px;">iframe loading</div>

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Because XMLHttpReponse synchronous operation is deprecated I came up with the following solution that wraps XMLHttpRequest. This allows ordered AJAX queries while still being asycnronous in nature, which is very useful for single use CSRF tokens.

It is also transparent so libraries such as jQuery will operate seamlessly.

/* wrap XMLHttpRequest for synchronous operation */
var XHRQueue = [];
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function()
{
  var xhr   = new _XMLHttpRequest();
  var _send = xhr.send;

  xhr.send = function()
  {
    /* queue the request, and if it's the first, process it */
    XHRQueue.push([this, arguments]);
    if (XHRQueue.length == 1)
      this.processQueue();
  };

  xhr.processQueue = function()
  {
    var call = XHRQueue[0];
    var xhr  = call[0];
    var args = call[1];

    /* you could also set a CSRF token header here */

    /* send the request */
    _send.apply(xhr, args);
  };

  xhr.addEventListener('load', function(e)
  {
    /* you could also retrieve a CSRF token header here */

    /* remove the completed request and if there is more, trigger the next */
    XHRQueue.shift();
    if (XHRQueue.length)
      this.processQueue();
  });

  return xhr;
};

How to check if IsNumeric

There's the TryParse method, which returns a bool indicating if the conversion was successful.

Is there "\n" equivalent in VBscript?

For replace you can use vbCrLf:

Replace(string, vbCrLf, "")

You can also use chr(13)+chr(10).

I seem to remember in some odd cases that chr(10) comes before chr(13).

How do you hide the Address bar in Google Chrome for Chrome Apps?

Hitting F11 may work for you.(Full-screen mode)

It appears that the hiding the address bar without going full screen is no longer an option:http://productforums.google.com/forum/#!topic/chrome/d7LfleRNX7M

use video as background for div

Pure CSS method

It is possible to center a video inside an element just like a cover sized background-image without JS using the object-fit attribute or CSS Transforms.

2021 answer: object-fit

As pointed in the comments, it is possible to achieve the same result without CSS transform, but using object-fit, which I think it's an even better option for the same result:

_x000D_
_x000D_
.video-container {
    height: 300px;
    width: 300px;
    position: relative;
}

.video-container video {
  width: 100%;
  height: 100%;
  position: absolute;
  object-fit: cover;
  z-index: 0;
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
    <video autoplay muted loop>
        <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
    </video>
    <div class="caption">
      <h2>Your caption here</h2>
    </div>
</div>
_x000D_
_x000D_
_x000D_


Previous answer: CSS Transform

You can set a video as a background to any HTML element easily thanks to transform CSS property.

Note that you can use the transform technique to center vertically and horizontally any HTML element.

_x000D_
_x000D_
.video-container {
  height: 300px;
  width: 300px;
  overflow: hidden;
  position: relative;
}

.video-container video {
  min-width: 100%;
  min-height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
  <video autoplay muted loop>
    <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
  </video>
  <div class="caption">
    <h2>Your caption here</h2>
  </div>
</div>
_x000D_
_x000D_
_x000D_

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

How to get WooCommerce order details

$order = new WC_Order(get_query_var('order-received'));

How do you save/store objects in SharedPreferences on Android?

Using Delegation Kotlin we can easily put and get data from shared preferences.

    inline fun <reified T> Context.sharedPrefs(key: String) = object : ReadWriteProperty<Any?, T> {

        val sharedPrefs by lazy { [email protected]("APP_DATA", Context.MODE_PRIVATE) }
        val gson by lazy { Gson() }
        var newData: T = (T::class.java).newInstance()

        override fun getValue(thisRef: Any?, property: KProperty<*>): T {
            return getPrefs()
        }

        override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
            this.newData = value
            putPrefs(newData)
        }

        fun putPrefs(value: T?) {
            sharedPrefs.edit {
                when (value) {
                    is Int -> putInt(key, value)
                    is Boolean -> putBoolean(key, value)
                    is String -> putString(key, value)
                    is Long -> putLong(key, value)
                    is Float -> putFloat(key, value)
                    is Parcelable -> putString(key, gson.toJson(value))
                    else          -> throw Throwable("no such type exist to put data")
                }
            }
        }

        fun getPrefs(): T {
            return when (newData) {
                       is Int -> sharedPrefs.getInt(key, 0) as T
                       is Boolean -> sharedPrefs.getBoolean(key, false) as T
                       is String -> sharedPrefs.getString(key, "") as T ?: "" as T
                       is Long -> sharedPrefs.getLong(key, 0L) as T
                       is Float -> sharedPrefs.getFloat(key, 0.0f) as T
                       is Parcelable -> gson.fromJson(sharedPrefs.getString(key, "") ?: "", T::class.java)
                       else          -> throw Throwable("no such type exist to put data")
                   } ?: newData
        }

    }

    //use this delegation in activity and fragment in following way
        var ourData by sharedPrefs<String>("otherDatas")

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

Return sql rows where field contains ONLY non-alphanumeric characters

This will not work correctly, e.g. abcÑxyz will pass thru this as it has a,b,c... you need to work with Collate or check each byte.

How to force child div to be 100% of parent div's height without specifying parent's height?

I find that setting the two columns to display: table-cell; instead of float: left; works well.

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

javascript - Create Simple Dynamic Array

Update: micro-optimizations like this one are just not worth it, engines are so smart these days that I would advice in the 2020 to simply just go with var arr = [];.

Here is how I would do it:

var mynumber = 10;
var arr = new Array(mynumber);

for (var i = 0; i < mynumber; i++) {
    arr[i] = (i + 1).toString();
}

My answer is pretty much the same of everyone, but note that I did something different:

  • It is better if you specify the array length and don't force it to expand every time

So I created the array with new Array(mynumber);

How to keep :active css style after clicking an element

The :target-pseudo selector is made for these type of situations: http://reference.sitepoint.com/css/pseudoclass-target

It is supported by all modern browsers. To get some IE versions to understand it you can use something like Selectivizr

Here is a tab example with :target-pseudo selector.

MS SQL compare dates?

The simple one line solution is

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')=0

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')<=1

datediff(dd,'2010-12-31 15:13:48.593','2010-12-31 00:00:00.000')>=1

You can try various option with this other than "dd"

Finding what branch a Git commit came from

Update December 2013:

sschuberth comments

git-what-branch (Perl script, see below) does not seem to be maintained anymore. git-when-merged is an alternative written in Python that's working very well for me.

It is based on "Find merge commit which include a specific commit".

git when-merged [OPTIONS] COMMIT [BRANCH...]

Find when a commit was merged into one or more branches.
Find the merge commit that brought COMMIT into the specified BRANCH(es).

Specifically, look for the oldest commit on the first-parent history of BRANCH that contains the COMMIT as an ancestor.


Original answer September 2010:

Sebastien Douche just twitted (16 minutes before this SO answer):

git-what-branch: Discover what branch a commit is on, or how it got to a named branch

This is a Perl script from Seth Robertson that seems very interesting:

SYNOPSIS

git-what-branch [--allref] [--all] [--topo-order | --date-order ]
[--quiet] [--reference-branch=branchname] [--reference=reference]
<commit-hash/tag>...

OVERVIEW

Tell us (by default) the earliest causal path of commits and merges to cause the requested commit got onto a named branch. If a commit was made directly on a named branch, that obviously is the earliest path.

By earliest causal path, we mean the path which merged into a named branch the earliest, by commit time (unless --topo-order is specified).

PERFORMANCE

If many branches (e.g. hundreds) contain the commit, the system may take a long time (for a particular commit in the Linux tree, it took 8 second to explore a branch, but there were over 200 candidate branches) to track down the path to each commit.
Selection of a particular --reference-branch --reference tag to examine will be hundreds of times faster (if you have hundreds of candidate branches).

EXAMPLES

 # git-what-branch --all 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4
 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4 first merged onto master using the following minimal temporal path:
   v2.6.12-rc3-450-g1f9c381 merged up at v2.6.12-rc3-590-gbfd4bda (Thu May  5 08:59:37 2005)
   v2.6.12-rc3-590-gbfd4bda merged up at v2.6.12-rc3-461-g84e48b6 (Tue May  3 18:27:24 2005)
   v2.6.12-rc3-461-g84e48b6 is on master
   v2.6.12-rc3-461-g84e48b6 is on v2.6.12-n
   [...]

This program does not take into account the effects of cherry-picking the commit of interest, only merge operations.

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

Upgraded from EF5 to EF6 nuget a while back and kept encountering this issue. I'd temp fix it by updating the generated code to reference System.Data.Entity.Core.Objects, but after generation it would be changed back again (as expected since its generated).

This solved the problem for good:

http://msdn.microsoft.com/en-us/data/upgradeef6

If you have any models created with the EF Designer, you will need to update the code generation templates to generate EF6 compatible code. Note: There are currently only EF 6.x DbContext Generator templates available for Visual Studio 2012 and 2013.

  1. Delete existing code-generation templates. These files will typically be named <edmx_file_name>.tt and <edmx_file_name>.Context.tt and be nested under your edmx file in Solution Explorer. You can select the templates in Solution Explorer and press the Del key to delete them.
    Note: In Web Site projects the templates will not be nested under your edmx file, but listed alongside it in Solution Explorer.
    Note: In VB.NET projects you will need to enable 'Show All Files' to be able to see the nested template files.
  2. Add the appropriate EF 6.x code generation template. Open your model in the EF Designer, right-click on the design surface and select Add Code Generation Item...
    • If you are using the DbContext API (recommended) then EF 6.x DbContext Generator will be available under the Data tab.
      Note: If you are using Visual Studio 2012, you will need to install the EF 6 Tools to have this template. See Get Entity Framework for details.
    • If you are using the ObjectContext API then you will need to select the Online tab and search for EF 6.x EntityObject Generator.
  3. If you applied any customizations to the code generation templates you will need to re-apply them to the updated templates.

How to query first 10 rows and next time query other 10 rows from table

for first 10 rows...

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 0,10

for next 10 rows

SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT 10,10

Android - how to make a scrollable constraintlayout?

This is how I resolved it:
If you are using Nested ScrollView i.e. ScrollView within a ConstraintLayout then use the following configuration for the ScrollView instead of "WRAP_CONTENT" or "MATCH_PARENT":


<ScrollView
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/someOtherWidget"
    app:layout_constraintTop_toTopOf="parent">

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

jQuery iframe load() event?

Along the lines of Tim Down's answer but leveraging jQuery (mentioned by the OP) and loosely coupling the containing page and the iframe, you could do the following:

In the iframe:

<script>
    $(function() {
        var w = window;
        if (w.frameElement != null
                && w.frameElement.nodeName === "IFRAME"
                && w.parent.jQuery) {
            w.parent.jQuery(w.parent.document).trigger('iframeready');
        }
    });
</script>

In the containing page:

<script>
    function myHandler() {
        alert('iframe (almost) loaded');
    }
    $(document).on('iframeready', myHandler);
</script>

The iframe fires an event on the (potentially existing) parent window's document - please beware that the parent document needs a jQuery instance of itself for this to work. Then, in the parent window you attach a handler to react to that event.

This solution has the advantage of not breaking when the containing page does not contain the expected load handler. More generally speaking, it shouldn't be the concern of the iframe to know its surrounding environment.

Please note, that we're leveraging the DOM ready event to fire the event - which should be suitable for most use cases. If it's not, simply attach the event trigger line to the window's load event like so:

$(window).on('load', function() { ... });

Fixed header, footer with scrollable content

If you're targeting browsers supporting flexible boxes you could do the following.. http://jsfiddle.net/meyertee/AH3pE/

HTML

<div class="container">
    <header><h1>Header</h1></header>
    <div class="body">Body</div>
    <footer><h3>Footer</h3></footer>
</div>

CSS

.container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
}

header {
    flex-shrink: 0;
}
.body{
    flex-grow: 1;
    overflow: auto;
    min-height: 2em;
}
footer{
    flex-shrink: 0;
}

Update:
See "Can I use" for browser support of flexible boxes.

Create a table without a header in Markdown

You may be able to hide a heading if you can add the following CSS:

<style>
    th {
        display: none;
    }
</style>

This is a bit heavy-handed and doesn’t distinguish between tables, but it may do for a simple task.

What are the options for (keyup) in Angular2?

These are the options currently documented in the tests: ctrl, shift, enter and escape. These are some valid examples of key bindings:

keydown.control.shift.enter
keydown.control.esc

You can track this here while no official docs exist, but they should be out soon.

Extract year from date

For some time now, you can also only rely on the data.table package and its IDate class plus associated functions (Check ?as.IDate()). So, no need to additionally install lubridate.

require(data.table)

a <- c("01/01/2009", "01/01/2010" , "01/01/2011")
year(as.IDate(a, '%d/%m/%Y')) # all data.table functions

What is the difference between Scrum and Agile Development?

At an outset what I can say is - Agile is an evolutionary methodology from Unified Process which focuses on Iterative & Incremental Development (IID). IID emphasizes iterative development more on construction phases (actual coding) and incremental deliveries. It wouldn't emphasize more on Requirements Analysis (Inception) and Design (Elaboration) being handled in the iterations itself. So, Iteration here is not a "mini project by itself".

In Agile, we take this IDD a bit further, adding more realities like Team Collaboration, Evolutionary Requirements and Design etc. And SCRUM is the tool to enable it by considering the human factors and building around 'Wisdom of the Group' principle. So, Sprint here is a "mini project by itself" bettering a pure IID model.

So, iterations implemented in Agile way are, yes, theoretically Sprints (highlighting the size of the iterations being small and deliveries being quick). I don't really differentiate between Agile and SCRUM and I see that SCRUM is a natural way of putting the Agile principles into use.

How to use sed to replace only the first occurrence in a file?

If anyone came here to replace a character for the first occurrence in all lines (like myself), use this:

sed '/old/s/old/new/1' file

-bash-4.2$ cat file
123a456a789a
12a34a56
a12
-bash-4.2$ sed '/a/s/a/b/1' file
123b456a789a
12b34a56
b12

By changing 1 to 2 for example, you can replace all the second a's only instead.

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had the same problem, you have to load first the Moment.js file!

_x000D_
_x000D_
<script src="path/moment.js"></script>_x000D_
<script src="path/bootstrap-datetimepicker.js"></script>
_x000D_
_x000D_
_x000D_

How to convert a data frame column to numeric type?

Tim is correct, and Shane has an omission. Here are additional examples:

R> df <- data.frame(a = as.character(10:15))
R> df <- data.frame(df, num = as.numeric(df$a), 
                        numchr = as.numeric(as.character(df$a)))
R> df
   a num numchr
1 10   1     10
2 11   2     11
3 12   3     12
4 13   4     13
5 14   5     14
6 15   6     15
R> summary(df)
  a          num           numchr    
 10:1   Min.   :1.00   Min.   :10.0  
 11:1   1st Qu.:2.25   1st Qu.:11.2  
 12:1   Median :3.50   Median :12.5  
 13:1   Mean   :3.50   Mean   :12.5  
 14:1   3rd Qu.:4.75   3rd Qu.:13.8  
 15:1   Max.   :6.00   Max.   :15.0  
R> 

Our data.frame now has a summary of the factor column (counts) and numeric summaries of the as.numeric() --- which is wrong as it got the numeric factor levels --- and the (correct) summary of the as.numeric(as.character()).

Formatting PowerShell Get-Date inside string

Instead of using string interpolation you could simply format the DateTime using the ToString("u") method and concatenate that with the rest of the string:

$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u") 

How to enable CORS in flask

Try the following decorators:

@app.route('/email/',methods=['POST', 'OPTIONS']) #Added 'Options'
@crossdomain(origin='*')                          #Added
def hello_world():
    name=request.form['name']
    email=request.form['email']
    phone=request.form['phone']
    description=request.form['description']

    mandrill.send_email(
        from_email=email,
        from_name=name,
        to=[{'email': app.config['QOLD_SUPPORT_EMAIL']}],
        text="Phone="+phone+"\n\n"+description
    )

    return '200 OK'

if __name__ == '__main__':
    app.run()

This decorator would be created as follows:

from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper


def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):

    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator

You can also check out this package Flask-CORS

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

The root problem is that WebKit browsers (Safari and Chrome) load JavaScript and CSS information in parallel. Thus, JavaScript may execute before the styling effects of CSS have been computed, returning the wrong answer. In jQuery, I've found that the solution is to wait until document.readyState == 'complete', .e.g.,

jQuery(document).ready(function(){
  if (jQuery.browser.safari && document.readyState != "complete"){
    //console.info('ready...');
    setTimeout( arguments.callee, 100 );
    return;
  } 
  ... (rest of function) 

As far as width and height goes... depending on what you are doing you may want offsetWidth and offsetHeight, which include things like borders and padding.

Powershell send-mailmessage - email to multiple recipients

That's right, each address needs to be quoted. If you have multiple addresses listed on the command line, the Send-MailMessage likes it if you specify both the human friendly and the email address parts.

Maven and adding JARs to system scope

Try this configuration. It worked for me:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <warSourceDirectory>mywebRoot</warSourceDirectory>
        <warSourceExcludes>source\**,build\**,dist\**,WEB-INF\lib\*,
            WEB-INF\classes\**,build.*
        </warSourceExcludes>
        <webXml>myproject/source/deploiement/web.xml</webXml>
        <webResources>
            <resource>
                <directory>mywebRoot/WEB-INF/lib</directory>
                <targetPath>WEB-INF/lib</targetPath>
                <includes>
                        <include>mySystemJar1.jar.jar</include>
                         <include>mySystemJar2.jar</include>
                   </includes>
            </resource>
        </webResources>
    </configuration>
</plugin>

How can I generate an HTML report for Junit results?

There are multiple options available for generating HTML reports for Selenium WebDriver scripts.

1. Use the JUNIT TestWatcher class for creating your own Selenium HTML reports

The TestWatcher JUNIT class allows overriding the failed() and succeeded() JUNIT methods that are called automatically when JUNIT tests fail or pass.

The TestWatcher JUNIT class allows overriding the following methods:

  • protected void failed(Throwable e, Description description)

failed() method is invoked when a test fails

  • protected void finished(Description description)

finished() method is invoked when a test method finishes (whether passing or failing)

  • protected void skipped(AssumptionViolatedException e, Description description)

skipped() method is invoked when a test is skipped due to a failed assumption.

  • protected void starting(Description description)

starting() method is invoked when a test is about to start

  • protected void succeeded(Description description)

succeeded() method is invoked when a test succeeds

See below sample code for this case:

import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class TestClass2 extends WatchManClassConsole {

    @Test public void testScript1() {
        assertTrue(1 < 2); >
    }

    @Test public void testScript2() {
        assertTrue(1 > 2);
    }

    @Test public void testScript3() {
        assertTrue(1 < 2);
    }

    @Test public void testScript4() {
        assertTrue(1 > 2);
    }
}

import org.junit.Rule; 
import org.junit.rules.TestRule; 
import org.junit.rules.TestWatcher; 
import org.junit.runner.Description; 
import org.junit.runners.model.Statement; 

public class WatchManClassConsole {

    @Rule public TestRule watchman = new TestWatcher() { 

        @Override public Statement apply(Statement base, Description description) { 
            return super.apply(base, description); 
        } 

        @Override protected void succeeded(Description description) { 
            System.out.println(description.getDisplayName() + " " + "success!"); 
        } 

        @Override protected void failed(Throwable e, Description description) { 
            System.out.println(description.getDisplayName() + " " + e.getClass().getSimpleName()); 
        }
    }; 
}

2. Use the Allure Reporting framework

Allure framework can help with generating HTML reports for your Selenium WebDriver projects.

The reporting framework is very flexible and it works with many programming languages and unit testing frameworks.

You can read everything about it at http://allure.qatools.ru/.

You will need the following dependencies and plugins to be added to your pom.xml file

  1. maven surefire
  2. aspectjweaver
  3. allure adapter

See more details including code samples on this article: http://test-able.blogspot.com/2015/10/create-selenium-html-reports-with-allure-framework.html

Counting repeated characters in a string in Python

I can count the number of days I know Python on my two hands so forgive me if I answer something silly :)

Instead of using a dict, I thought why not use a list? I'm not sure how lists and dictionaries are implemented in Python so this would have to be measured to know what's faster.

If this was C++ I would just use a normal c-array/vector for constant time access (that would definitely be faster) but I don't know what the corresponding datatype is in Python (if there's one...):

count = [0 for i in range(26)]

for c in ''.join(s.lower().split()): # get rid of whitespaces and capital letters
    count[ord(c) - 97] += 1          # ord('a') == 97

It's also possible to make the list's size ord('z') and then get rid of the 97 subtraction everywhere, but if you optimize, why not all the way :)

EDIT: A commenter suggested that the join/split is not worth the possible gain of using a list, so I thought why not get rid of it:

count = [0 for i in range(26)]

for c in s:
    if c.isalpha(): count[ord(c.lower()) - 97] += 1

Print time in a batch file (milliseconds)

%time% should work, provided enough time has elapsed between calls:

@echo OFF

@echo %time%
ping -n 1 -w 1 127.0.0.1 1>nul
@echo %time%

On my system I get the following output:

6:46:13.50
6:46:13.60

List of all special characters that need to be escaped in a regex

Assuming that you have and trust (to be authoritative) the list of escape characters Java regex uses (would be nice if these characters were exposed in some Pattern class member) you can use the following method to escape the character if it is indeed necessary:

private static final char[] escapeChars = { '<', '(', '[', '{', '\\', '^', '-', '=', '$', '!', '|', ']', '}', ')', '?', '*', '+', '.', '>' };

private static String regexEscape(char character) {
    for (char escapeChar : escapeChars) {
        if (character == escapeChar) {
            return "\\" + character;
        }
    }
    return String.valueOf(character);
}

javascript code to check special characters

Try This one.

_x000D_
_x000D_
function containsSpecialCharacters(str){_x000D_
    var regex = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;_x000D_
 return regex.test(str);_x000D_
}
_x000D_
_x000D_
_x000D_

How to pass text in a textbox to JavaScript function?

You could either access the element’s value by its name:

document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"

So:

<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />

Or you assign an ID to the element that then identifies it and you can access it with getElementById:

<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />

How can I inject a property value into a Spring Bean which was configured using annotations?

Before we get Spring 3 - which allows you to inject property constants directly into your beans using annotations - I wrote a sub-class of the PropertyPlaceholderConfigurer bean that does the same thing. So, you can mark up your property setters and Spring will autowire your properties into your beans like so:

@Property(key="property.key", defaultValue="default")
public void setProperty(String property) {
    this.property = property;
}

The Annotation is as follows:

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Property {
    String key();
    String defaultValue() default "";
}

The PropertyAnnotationAndPlaceholderConfigurer is as follows:

public class PropertyAnnotationAndPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    private static Logger log = Logger.getLogger(PropertyAnnotationAndPlaceholderConfigurer.class);

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties properties) throws BeansException {
        super.processProperties(beanFactory, properties);

        for (String name : beanFactory.getBeanDefinitionNames()) {
            MutablePropertyValues mpv = beanFactory.getBeanDefinition(name).getPropertyValues();
            Class clazz = beanFactory.getType(name);

            if(log.isDebugEnabled()) log.debug("Configuring properties for bean="+name+"["+clazz+"]");

            if(clazz != null) {
                for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
                    Method setter = property.getWriteMethod();
                    Method getter = property.getReadMethod();
                    Property annotation = null;
                    if(setter != null && setter.isAnnotationPresent(Property.class)) {
                        annotation = setter.getAnnotation(Property.class);
                    } else if(setter != null && getter != null && getter.isAnnotationPresent(Property.class)) {
                        annotation = getter.getAnnotation(Property.class);
                    }
                    if(annotation != null) {
                        String value = resolvePlaceholder(annotation.key(), properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                        if(StringUtils.isEmpty(value)) {
                            value = annotation.defaultValue();
                        }
                        if(StringUtils.isEmpty(value)) {
                            throw new BeanConfigurationException("No such property=["+annotation.key()+"] found in properties.");
                        }
                        if(log.isDebugEnabled()) log.debug("setting property=["+clazz.getName()+"."+property.getName()+"] value=["+annotation.key()+"="+value+"]");
                        mpv.addPropertyValue(property.getName(), value);
                    }
                }

                for(Field field : clazz.getDeclaredFields()) {
                    if(log.isDebugEnabled()) log.debug("examining field=["+clazz.getName()+"."+field.getName()+"]");
                    if(field.isAnnotationPresent(Property.class)) {
                        Property annotation = field.getAnnotation(Property.class);
                        PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

                        if(property.getWriteMethod() == null) {
                            throw new BeanConfigurationException("setter for property=["+clazz.getName()+"."+field.getName()+"] not available.");
                        }

                        Object value = resolvePlaceholder(annotation.key(), properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                        if(value == null) {
                            value = annotation.defaultValue();
                        }
                        if(value == null) {
                            throw new BeanConfigurationException("No such property=["+annotation.key()+"] found in properties.");
                        }
                        if(log.isDebugEnabled()) log.debug("setting property=["+clazz.getName()+"."+field.getName()+"] value=["+annotation.key()+"="+value+"]");
                        mpv.addPropertyValue(property.getName(), value);
                    }
                }
            }
        }
    }

}

Feel free to modify to taste

Pass multiple parameters to rest API - Spring

Yes its possible to pass JSON object in URL

queryString = "{\"left\":\"" + params.get("left") + "}";
 httpRestTemplate.exchange(
                    Endpoint + "/A/B?query={queryString}",
                    HttpMethod.GET, entity, z.class, queryString);

CSS for the "down arrow" on a <select> element?

The drop-down is platform-level element, you can't apply CSS to it.

You can overlay an image on top of it using CSS, and call the click event in the element beneath.

How do you create a Distinct query in HQL

do something like this next time

 Criteria crit = (Criteria) session.
                  createCriteria(SomeClass.class).
                  setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

 List claz = crit.list();

Java; String replace (using regular expressions)?

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";

String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

I sought online for an answer but it seems there is no one proper solution to my case: At the very beginning, everything works well as follows:

@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
    private Repository repository;
    private Service service;
}

Then I am trying to add a map to cache something and it becomes this:

@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
    private Repository repository;
    private Service service;
    Map<String, String> testMap;
}

Boom!

Description:

Parameter 4 of constructor in *.GroupService required a bean of type 'java.lang.String' that could not be found.


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

I removed the @AllArgsConstructor(onConstructor = @__(@Autowired)) and add @Autowired for each repository and service except the Map<String, String>. It just works as before.

@Slf4j
@Service
public class SecurityGroupService {
    @Autowired
    private Repository repository;
    @Autowired
    private Service service;
    Map<String, String> testMap;
}

Hope this might be helpful.

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

Oracle 'Partition By' and 'Row_Number' keyword

I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.

R: invalid multibyte string

I had a similarly strange problem with a file from the program e-prime (edat -> SPSS conversion), but then I discovered that there are many additional encodings you can use. this did the trick for me:

tbl <- read.delim("dir/file.txt", fileEncoding="UCS-2LE")

using sql count in a case statement

Close... try:

select 
   Sum(case when rsp_ind = 0 then 1 Else 0 End) as 'New',
   Sum(case when rsp_ind = 1 then 1 else 0 end) as 'Accepted'
from tb_a

phpmyadmin "no data received to import" error, how to fix?

I never succeeded importing dumb files using phpmyadmin or phpMyBackupPro better is to go to console or command line ( whatever it's called in mac ) and do the following:

mysql -u username -p databasename

replace username with the username you use to connect to mysql, then it will ask you to enter the password for that username, and that's it

you can import any size of dumb using this method

How to build and fill pandas dataframe from for loop?

Make a list of tuples with your data and then create a DataFrame with it:

d = []
for p in game.players.passing():
    d.append((p, p.team, p.passer_rating()))

pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))

A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.

Testing functions:

def with_tuples(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append((x-1, x, x+1))

    return pd.DataFrame(res, columns=("a", "b", "c"))

def with_dict(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append({"a":x-1, "b":x, "c":x+1})

    return pd.DataFrame(res)

Results:

%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop

%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop

How can I make space between two buttons in same div?

if use Bootstrap, you can change with style like: If you want only in one page, then betwen head tags add .btn-group btn{margin-right:1rem;}

If is for all the web site add to css file

XSL if: test with multiple test conditions

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.
</xsl:if>

Convert iterator to pointer?

For example, my vector<int> foo contains (5,2,6,87,251). A function takes vector<int>* and I want to pass it a pointer to (2,6,87,251).

A pointer to a vector<int> is not at all the same thing as a pointer to the elements of the vector.

In order to do this you will need to create a new vector<int> with just the elements you want in it to pass a pointer to. Something like:

 vector<int> tempVector( foo.begin()+1, foo.end());

 // now you can pass &tempVector to your function

However, if your function takes a pointer to an array of int, then you can pass &foo[1].

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

In Ecmascript 6,

var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

var res = Object.entries(obj);

console.log(res);

fiddle

What is the difference between Cygwin and MinGW?

Note that utility behaviour can genuinely vary between the two.

For example, Cygwin tar can fork - because fork() is supported in the DLL - where the mingw version cannot. This is a problem when trying to compile mysql from source.

Set the maximum character length of a UITextField in Swift

Simply just check with the number of characters in the string

  1. Add a delegate to view controller ans asign delegate
    class YorsClassName : UITextFieldDelegate {

    }
  1. check the number of chars allowed for textfield
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text?.count == 1 {
        return false
    }
    return true
}

Note: Here I checked for only char allowed in textField

How do I access (read, write) Google Sheets spreadsheets with Python?

(Jun-Dec 2016) Most answers here are now out-of-date as: 1) GData APIs are the previous generation of Google APIs, and that's why it was hard for @Josh Brown to find that old GData Docs API documentation. While not all GData APIs have been deprecated, all newer Google APIs do not use the Google Data protocol; and 2) Google released a new Google Sheets API (not GData). In order to use the new API, you need to get the Google APIs Client Library for Python (it's as easy as pip install -U google-api-python-client [or pip3 for Python 3]) and use the latest Sheets API v4+, which is much more powerful & flexible than older API releases.

Here's one code sample from the official docs to help get you kickstarted. However, here are slightly longer, more "real-world" examples of using the API you can learn from (videos plus blog posts):

The latest Sheets API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resizing rows/columns, adding pivot tables, creating charts, etc.), but NOT as if it was some database that you could perform searches on and get selected rows from. You'd basically have to build a querying layer on top of the API that does this. One alternative is to use the Google Charts Visualization API query language, which does support SQL-like querying. You can also query from within the Sheet itself. Be aware that this functionality existed before the v4 API, and that the security model was updated in Aug 2016. To learn more, check my G+ reshare to a full write-up from a Google Developer Expert.

Also note that the Sheets API is primarily for programmatically accessing spreadsheet operations & functionality as described above, but to perform file-level access such as imports/exports, copy, move, rename, etc., use the Google Drive API instead. Examples of using the Drive API:

(*) - TL;DR: upload plain text file to Drive, import/convert to Google Docs format, then export that Doc as PDF. Post above uses Drive API v2; this follow-up post describes migrating it to Drive API v3, and here's a developer video combining both "poor man's converter" posts.

To learn more about how to use Google APIs with Python in general, check out my blog as well as a variety of Google developer videos (series 1 and series 2) I'm producing.

ps. As far as Google Docs goes, there isn't a REST API available at this time, so the only way to programmatically access a Doc is by using Google Apps Script (which like Node.js is JavaScript outside of the browser, but instead of running on a Node server, these apps run in Google's cloud; also check out my intro video.) With Apps Script, you can build a Docs app or an add-on for Docs (and other things like Sheets & Forms).

UPDATE Jul 2018: The above "ps." is no longer true. The G Suite developer team pre-announced a new Google Docs REST API at Google Cloud NEXT '18. Developers interested in getting into the early access program for the new API should register at https://developers.google.com/docs.

UPDATE Feb 2019: The Docs API launched to preview last July is now available generally to all... read the launch post for more details.

UPDATE Nov 2019: In an effort to bring G Suite and GCP APIs more inline with each other, earlier this year, all G Suite code samples were partially integrated with GCP's newer (lower-level not product) Python client libraries. The way auth is done is similar but (currently) requires a tiny bit more code to manage token storage, meaning rather than our libraries manage storage.json, you'll store them using pickle (token.pickle or whatever name you prefer) instead, or choose your own form of persistent storage. For you readers here, take a look at the updated Python quickstart example.

How to make Visual Studio copy a DLL file to the output directory?

(This answer only applies to C# not C++, sorry I misread the original question)

I've got through DLL hell like this before. My final solution was to store the unmanaged DLLs in the managed DLL as binary resources, and extract them to a temporary folder when the program launches and delete them when it gets disposed.

This should be part of the .NET or pinvoke infrastructure, since it is so useful.... It makes your managed DLL easy to manage, both using Xcopy or as a Project reference in a bigger Visual Studio solution. Once you do this, you don't have to worry about post-build events.

UPDATE:

I posted code here in another answer https://stackoverflow.com/a/11038376/364818

Why maven settings.xml file is not there?

You can verify where your Setting.xml is by pressing shortcut Ctrl+3, you will see Quick Access on top right side of Eclipse, then search setting.xml in searchbox. If you got setting.xml it will show up in search. Click that, and it will open the window showing directory path wherever it is stored. Your Maven Global Settings should be as such:

Global Setting C:\maven\apache-maven-3.5.0\conf\settings.xml
User Setting %userprofile%\\.m2\setting.xml
You can use global setting usually and leave the second option user setting untouched. Store your setting.xml in Global Setting

jQuery UI DatePicker to show year only

You can use this bootstrap datepicker

$("your-selector").datepicker({
    format: "yyyy",
    viewMode: "years", 
    minViewMode: "years"
});

"your-selector" you can use id(#your-selector) OR class(.your-selector).

HTML input textbox with a width of 100% overflows table cells

I usually set the width of my inputs to 99% to fix this:

input {
    width: 99%;
}

You can also remove the default styles, but that will make it less obvious that it is a text box. However, I will show the code for that anyway:

input {
    width: 100%;
    border-width: 0;
    margin: 0;
    padding: 0;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}

Ad@m

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

Right-Click on your project -> Properties -> Deployment Assembly.

On the Left-hand panel Click 'Add' and add the 'Project and External Dependencies'.

'Project and External Dependencies' will have all the spring related jars deployed along with your application

How to compare LocalDate instances Java 8

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day - otherDate.day);
        }
    }
    return cmp;
}

If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

Remove last specific character in a string c#

Try below

Something..TrimEnd(",".ToCharArray());

Regex to validate date format dd/mm/yyyy

Another answer which validates day (dd) depending upon the month (mm) and the year (yyyy) (i.e., also validates 29th Feb in leap years) and allows years ranging from 0001 to 9999 (0000 in a invalid year according to the Gregorian calendar)

^(?:(?:(?:0[1-9]|[12]\d|3[01])/(?:0[13578]|1[02])|(?:0[1-9]|[12]\d|30)/(?:0[469]|11)|(?:0[1-9]|1\d|2[0-8])/02)/(?!0000)\d{4}|(?:(?:0[1-9]|[12]\d)/02/(?:(?!0000)(?:[02468][048]|[13579][26])00|(?!..00)\d{2}(?:[02468][048]|[13579][26]))))$

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

Note that if you use SELECT FOR UPDATE to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE, then to check the affected row count.

add below line to my.cnf file

innodb_locks_unsafe_for_binlog = 1

#

1 - ON
0 - OFF

#

Interview Question: Merge two sorted singly linked lists without creating new nodes

I show below an iterative solution. A recursive solution would be more compact, but since we don't know the length of the lists, recursion runs the risk of stack overflow.

The basic idea is similar to the merge step in merge sort; we keep a pointer corresponding to each input list; at each iteration, we advance the pointer corresponding to the smaller element. However, there's one crucial difference where most people get tripped. In merge sort, since we use a result array, the next position to insert is always the index of the result array. For a linked list, we need to keep a pointer to the last element of the sorted list. The pointer may jump around from one input list to another depending on which one has the smaller element for the current iteration.

With that, the following code should be self-explanatory.

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (l1 == null) {
        return l2;
    }
    if (l2 == null) {
        return l1;
    }
    ListNode first = l1;
    ListNode second = l2;
    ListNode head = null;
    ListNode last = null;

    while (first != null && second != null) {
        if (first.val < second.val) {
            if (last != null) {
                last.next = first;
            }
            last = first;
            first = first.next;
        } else {
            if (last != null) {
                last.next = second;
            }
            last = second;
            second = second.next;
        }
        if (head == null) {
            head = last;
        }
    }

    if (first == null) {
        last.next = second;
    }
    if (second == null) {
        last.next = first;
    }

    return head;
}

Change user-agent for Selenium web-driver

To build on JJC's helpful answer that builds on Louis's helpful answer...

With PhantomJS 2.1.1-windows this line works:

driver.execute_script("return navigator.userAgent")

If it doesn't work, you can still get the user agent via the log (to build on Mma's answer):

from selenium import webdriver
import json
from fake_useragent import UserAgent

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)
driver = webdriver.PhantomJS(executable_path=r"your_path", desired_capabilities=dcap)
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('user agent: ', har['log']['entries'][0]['request']['headers'][1]['value'])

How can I calculate the difference between two ArrayLists?

You are just comparing strings.

Put the values in ArrayList A as keys in HashTable A.
Put the values in ArrayList B as keys in HashTable B.

Then, for each key in HashTable A, remove it from HashTable B if it exists.

What you are left with in HashTable B are the strings (keys) that were not values in ArrayList A.

C# (3.0) example added in response to request for code:

List<string> listA = new List<string>{"2009-05-18","2009-05-19","2009-05-21'"};
List<string> listB = new List<string>{"2009-05-18","2009-05-18","2009-05-19","2009-05-19","2009-05-20","2009-05-21","2009-05-21","2009-05-22"};

HashSet<string> hashA = new HashSet<string>();
HashSet<string> hashB = new HashSet<string>();

foreach (string dateStrA in listA) hashA.Add(dateStrA);
foreach (string dateStrB in listB) hashB.Add(dateStrB);

foreach (string dateStrA in hashA)
{
    if (hashB.Contains(dateStrA)) hashB.Remove(dateStrA);
}

List<string> result = hashB.ToList<string>();

Notice: Trying to get property of non-object error

@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error

Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid'] instead of $objData->token

What does the "undefined reference to varName" in C mean?

You need to link both a.o and b.o:

gcc -o program a.c b.c

If you have a main() in each file, you cannot link them together.

However, your a.c file contains a reference to doSomething() and expects to be linked with a source file that defines doSomething() and does not define any function that is defined in a.c (such as main()).

You cannot call a function in Process B from Process A. You cannot send a signal to a function; you send signals to processes, using the kill() system call.

The signal() function specifies which function in your current process (program) is going to handle the signal when your process receives the signal.

You have some serious work to do understanding how this is going to work - how ProgramA is going to know which process ID to send the signal to. The code in b.c is going to need to call signal() with dosomething as the signal handler. The code in a.c is simply going to send the signal to the other process.

How do I reference a local image in React?

First of all wrap the src in {}

Then if using Webpack; Instead of: <img src={"./logo.jpeg"} />

You may need to use require:

<img src={require('./logo.jpeg')} />


Another option would be to first import the image as such:

import logo from './logo.jpeg'; // with import

or ...

const logo = require('./logo.jpeg); // with require

then plug it in...

<img src={logo} />

I'd recommend this option especially if you're reusing the image source.

Visual Studio : short cut Key : Duplicate Line

in VS2019 and also in VS2017 you can select Tools->Options->Keyboard and you can choose in the scheme drop-down Resharper (Visual Studio) option, and you will get a mapping like if you were using Resharper, in this case Ctrl + D will do the trick for duplicating the line. Anyways, based on the documentation this should be out of the gate in Visual Studio 2017 Version 15.8 or greater

Checking if float is an integer

stdlib float modf (float x, float *ipart) splits into two parts, check if return value (fractional part) == 0.

Using DISTINCT along with GROUP BY in SQL Server

Perhaps not in the context that you have it, but you could use

SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA

You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.

Preprocessor check if multiple defines are not defined

FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.

main.c has a main wrapper like this:

#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
  // the true main() routine.
}

spi.c, serial.c and usb.c have main wrappers for their respective test code like this:

#ifdef TEST_USB
int main(int argc, char *argv[]) {
  // the  main() routine for testing the usb code.
}

config.h Which is included by all the c files has an entry like this:

// Uncomment below to test the serial
//#define TEST_SERIAL


// Uncomment below to test the spi code
//#define TEST_SPI

// Uncomment below to test the usb code
#define TEST_USB

Regex for checking if a string is strictly alphanumeric

100% alphanumeric RegEx (it contains only alphanumeric, not even integers & characters, only alphanumeric)

For example:

special char (not allowed)
123 (not allowed)
asdf (not allowed)
1235asdf (allowed)


String name="^[^<a-zA-Z>]\\d*[a-zA-Z][a-zA-Z\\d]*$";

Android Gradle Apache HttpClient does not exist?

After spending days on the subject, I managed to solve it finally. Unfortunately we need it if we want to use expansion files. The solution has been provided by a few people here, but for me the answers were missing a few minor detail that could have saved a lot of time for me. Here is the sequence of events for novices like me to save your precious time.

First I imported the "library" folder from D:\Users\Imre\AppData\Local\Android\sdk1\extras\google\play_licensing to the project by going into File, New, Import Module and navigating to the "library" folder. If you open the SDK Manager and click on "Launch Standalone SDK Manager" in the bottom of the popup screen, you can hover your pointer over the "Extras" folder down in the bottom and the small yellow info will tell you where you will find the package that you need to import.

Once that is done, go down to the "library" section in the left pane with "Project" and within it the "Android" tab open. Open the java section of the library and open the APKExpansionPolicy class. If you have errors and the import org.apache.http.NameValuePair and the import org.apache.http.client.utils.URLEncodedUtils are pale grey, open the build.gradle(Project:whatever) and make sure that in "buildscript" under "dependancies" you have the "classpath 'com.android.tools.build:gradle:1.5.0" included. The 1.5.0 might be different in your case. I guess it depends on your Studio version. Mine is 1.5.1. If yours is newer, you will be reminded to update the numbers.

After that, go to "build.gradle(Module:library) and include the "useLibrary 'org.apache.http.legacy' into the "android"section. Sync Now (R/H top corner) should be offered. Do it.

If you get further error messages (I wouldn't know it because I did it the other way round), the Apache files might be missing from your project, as apache is not supported anymore. Find them in C/D:Users/Yourname/AppData/Local/Android/Sdk/platforms/android-23/optional and copy/paste them into yourproject/app/libs folder. You should have an optional.json and an org.apache.http.legacy.jar file in there. You might be better off going to apache's website and dowloading the newest version: http://hc.apache.org/downloads.cgi Unzip it anywhere you want, open it, go to "lib", copy the httpclient-4.5.1.jar file and replace the org.apache.http.legacy.jar file with it.

Sync and rebuild/clean your project and it should be good to go.

Just in case, open your terminal (L/H bottom of Android Studio) and type in "gradlew clean". It will install a few things. Once it is done, type in "gradlew assemble". It will take a few minutes to finish, but it will give you the errors if you have any of course. If you cannot type in anything in the Terminal, launch command prompt (Windows button+R), type in cmd, hit OK, right click on the title of the small black popup screen (C:\WINDOWS\system32\cmd.exe), Properties, Options, in the bottom of the window check that "Use legacy console" is thicked. Restart A.Studio.

Good luck!

Css Move element from left to right animated

It's because you aren't giving the un-hovered state a right attribute.

right isn't set so it's trying to go from nothing to 0px. Obviously because it has nothing to go to, it just 'warps' over.

If you give the unhovered state a right:90%;, it will transition how you like.

Just as a side note, if you still want it to be on the very left of the page, you can use the calc css function.

Example:

right: calc(100% - 100px)
                     ^ width of div

You don't have to use left then.

Also, you can't transition using left or right auto and will give the same 'warp' effect.

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    background:red;_x000D_
    transition:2s;_x000D_
    -webkit-transition:2s;_x000D_
    -moz-transition:2s;_x000D_
    position:absolute;_x000D_
    right:calc(100% - 100px);_x000D_
}_x000D_
div:hover {_x000D_
  right:0;_x000D_
}
_x000D_
<p>_x000D_
  <b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
</p>_x000D_
<div></div>_x000D_
<p>Hover over the red square to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

CanIUse says that the calc() function only works on IE10+

Run JavaScript when an element loses focus

You're looking for the onblur event. Look here, for more details.

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

How to specify Memory & CPU limit in docker compose version 3

Docker Compose does not support the deploy key. It's only respected when you use your version 3 YAML file in a Docker Stack.

This message is printed when you add the deploy key to you docker-compose.yml file and then run docker-compose up -d

WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use docker stack deploy to deploy to a swarm.

The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:

Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.

Paging with LINQ for objects

_x000D_
_x000D_
var results = (medicineInfo.OrderBy(x=>x.id)_x000D_
                       .Skip((pages -1) * 2)_x000D_
                       .Take(2));
_x000D_
_x000D_
_x000D_

Python: 'break' outside loop

Because break can only be used inside a loop. It is used to break out of a loop (stop the loop).

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

Here is another one - ? - Unicode U+141E / CANADIAN SYLLABICS GLOTTAL STOP

Export JAR with Netbeans

You need to enable the option

Project Properties -> Build -> Packaging -> Build JAR after compiling

(but this is enabled by default)

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

I know this question is old, but the solution to my application, was different to the already suggested answers. If anyone else like me still have this issue, and none of the above answers works, this might be the problem:

I used a Network Credentials object to parse a windows username+password to a third party SOAP webservice. I had set the username="domainname\username", password="password" and domain="domainname". Now this game me that strange Ntlm and not NTLM error. To solve the problems, make sure not to use the domain parameter on the NetworkCredentials object if the domain name is included in the username with the backslash. So either remove domain name from the username and parse in domain parameter, or leave out the domain parameter. This solved my issue.

What is the difference between React Native and React?

It is a Hybrid tool for app development for both OS and android. You don't have to write a code for two times. It uses native components along with react. It also provides you the access to server (firebase). for further help follow the links: https://reactnative.dev/ https://nativebase.io/

How do I convert a factor into date format?

You were close. format= needs to be added to the as.Date call:

mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"

MySQL Fire Trigger for both Insert and Update

unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle

Is it bad practice to use break to exit a loop in Java?

If you know in advance where the loop will have to stop, it will probably improve code readability to state the condition in the for, while, or `do-while loop.

Otherwise, that's the exact use case for break.

What is callback in Android?

Here is a nice tutorial, which describes callbacks and the use-case well.

The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you".

Here's a example:

class A implements ICallback {
     MyObject o;
     B b = new B(this, someParameter);

     @Override
     public void callback(MyObject o){
           this.o = o;
     }
}

class B {
     ICallback ic;
     B(ICallback ic, someParameter){
         this.ic = ic;
     }

    new Thread(new Runnable(){
         public void run(){
             // some calculation
             ic.callback(myObject)
         }
    }).start(); 
}

interface ICallback{
    public void callback(MyObject o);
}

Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available.

In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity.

Check if any ancestor has a class using jQuery

You can use parents method with specified .class selector and check if any of them matches it:

if ($elem.parents('.left').length != 0) {
    //someone has this class
}

How to save and extract session data in codeigniter

initialize the Session class in the constructor of controller using

$this->load->library('session');

for example :

 function __construct()
   {
    parent::__construct();
    $this->load->model('user','',TRUE);
    $this->load->model('user_activity','',TRUE);
    $this->load->library('session');
   }

Check to see if python script is running

A technique that is handy on a Linux system is using domain sockets:

import socket
import sys
import time

def get_lock(process_name):
    # Without holding a reference to our socket somewhere it gets garbage
    # collected when the function exits
    get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)

    try:
        # The null byte (\0) means the socket is created 
        # in the abstract namespace instead of being created 
        # on the file system itself.
        # Works only in Linux
        get_lock._lock_socket.bind('\0' + process_name)
        print 'I got the lock'
    except socket.error:
        print 'lock exists'
        sys.exit()


get_lock('running_test')
while True:
    time.sleep(3)

It is atomic and avoids the problem of having lock files lying around if your process gets sent a SIGKILL

You can read in the documentation for socket.close that sockets are automatically closed when garbage collected.

Python virtualenv questions

After creating virtual environment copy the activate.bat file from Script folder of python and paste to it your environment and open cmd from your virtual environment and run activate.bat file.enter image description here

In Node.js, how do I "include" functions from my other files?

I just want to add, in case you need just certain functions imported from your tools.js, then you can use a destructuring assignment which is supported in node.js since version 6.4 - see node.green.


Example: (both files are in the same folder)

tools.js

module.exports = {
    sum: function(a,b) {
        return a + b;
    },
    isEven: function(a) {
        return a % 2 == 0;
    }
};

main.js

const { isEven } = require('./tools.js');

console.log(isEven(10));

output: true


This also avoids that you assign those functions as properties of another object as its the case in the following (common) assignment:

const tools = require('./tools.js');

where you need to call tools.isEven(10).


NOTE:

Don't forget to prefix your file name with the correct path - even if both files are in the same folder, you need to prefix with ./

From Node.js docs:

Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder.

How to compare strings in Bash

Using variables in if statements

if [ "$x" = "valid" ]; then
  echo "x has the value 'valid'"
fi

If you want to do something when they don't match, replace = with !=. You can read more about string operations and arithmetic operations in their respective documentation.

Why do we use quotes around $x?

You want the quotes around $x, because if it is empty, your Bash script encounters a syntax error as seen below:

if [ = "valid" ]; then

Non-standard use of == operator

Note that Bash allows == to be used for equality with [, but this is not standard.

Use either the first case wherein the quotes around $x are optional:

if [[ "$x" == "valid" ]]; then

or use the second case:

if [ "$x" = "valid" ]; then

Where can I view Tomcat log files in Eclipse?

if you're after the catalina.out log and you are using eclispe with tomcat, this works for me:

  • create catelina.out some where in your computer. In my case, I put it in logs directory of my tomcat install directory e.g: /opt/apache-tomcat-7.0.83/logs/catena.out
  • go to your eclipse, in the servers tab, double-click on the Tomcat Server. You will get a screen called Overview.
  • Click on "Open launch configuration". Then click on the "Common" tab.
  • At standard input and output section, check "output file", click on file system and then selected the folder where your create your catelina.out.
  • Finally, restart the Tomcat server.

How to get a certain element in a list, given the position?

Not very efficient, but if you must use a list, you can deference the iterator

*myList.begin()+N

How to set custom ActionBar color / style?

Custom Color:

 <style name="AppTheme" parent="Theme.AppCompat.Light">

                <item name="colorPrimary">@color/ColorPrimary</item>
                <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
                <!-- Customize your theme here. -->
     </style>

Custom Style:

 <style name="Theme.AndroidDevelopers" parent="android:style/Theme.Holo.Light">
        <item name="android:selectableItemBackground">@drawable/ad_selectable_background</item>
        <item name="android:popupMenuStyle">@style/MyPopupMenu</item>
        <item name="android:dropDownListViewStyle">@style/MyDropDownListView</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabStyle</item>
        <item name="android:actionDropDownStyle">@style/MyDropDownNav</item>
        <item name="android:listChoiceIndicatorMultiple">@drawable/ad_btn_check_holo_light</item>
        <item name="android:listChoiceIndicatorSingle">@drawable/ad_btn_radio_holo_light</item>
    </style>

For More: Android ActionBar

Function for 'does matrix contain value X?'

Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus

X = primes(20);
ismember([15 17],X)
ans =
      0    1

Since 15 is not prime, but 17 is, ismember has done its job well here.

Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.

~isempty(find(X == 15))
~isempty(find(X == 17))

or,

any(X == 15)
any(X == 17)

Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.

tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)

Import CSV to mysql table

First create a table in the database with same numbers of columns that are in the csv file.

Then use following query

LOAD DATA INFILE 'D:/Projects/testImport.csv' INTO TABLE cardinfo
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'

How to set ssh timeout?

ssh -o ConnectTimeout=10  <hostName>

Where 10 is time in seconds. This Timeout applies only to the creation of the connection.

How do I determine whether an array contains a particular value in Java?

Use the following (the contains() method is ArrayUtils.in() in this code):

ObjectUtils.java

public class ObjectUtils{

    /**
     * A null safe method to detect if two objects are equal.
     * @param object1
     * @param object2
     * @return true if either both objects are null, or equal, else returns false.
     */
    public static boolean equals(Object object1, Object object2){
        return object1==null ? object2==null : object1.equals(object2);
    }

}

ArrayUtils.java

public class ArrayUtils{

    /**
     * Find the index of of an object is in given array, starting from given inclusive index.
     * @param ts  Array to be searched in.
     * @param t  Object to be searched.
     * @param start  The index from where the search must start.
     * @return Index of the given object in the array if it is there, else -1.
     */
    public static <T> int indexOf(final T[] ts, final T t, int start){
        for(int i = start; i < ts.length; ++i)
            if(ObjectUtils.equals(ts[i], t))
                return i;
        return -1;
    }

    /**
     * Find the index of of an object is in given array, starting from 0;
     * @param ts  Array to be searched in.
     * @param t  Object to be searched.
     * @return  indexOf(ts, t, 0)
     */
    public static <T> int indexOf(final T[] ts, final T t){
        return indexOf(ts, t, 0);
    }

    /**
     * Detect if the given object is in the given array.
     * @param ts  Array to be searched in.
     * @param t  Object to be searched.
     * @return  If indexOf(ts, t) is greater than -1.
     */
    public static <T> boolean in(final T[] ts, final T t){
        return indexOf(ts, t) > -1 ;
    }

}

As you can see in the code above, that there are other utility methods ObjectUtils.equals() and ArrayUtils.indexOf(), that were used at other places as well.

How to call a php script/function on a html button click

Modify the_script.php like this.

<script>
the_function() {
    alert("You win");
}
</script>

how to change the dist-folder path in angular-cli after 'ng build'

for github pages I Use

ng build --prod --base-href "https://<username>.github.io/<RepoName>/" --output-path=docs

This is what that copies output into the docs folder : --output-path=docs

Batch Script to Run as Administrator

Don't waste your time, use this one line command to run command line as administrator:

echo createobject("shell.application").shellexecute "cmd.exe",,,"runas",1 > runas.vbs & start /wait runas.vbs & del /f runas.vbs

if you want to start any application with administrator privilege you will just write the hole path for this application like this notepad++ in my program files for example :

echo createobject("shell.application").shellexecute "%programfiles%\Notepad++\notepad++.exe",,,"runas",1 > runas.vbs & start /wait runas.vbs

HTML5 and frameborder

I found a nice work around that will allow it to work in IE7 here. It bypasses the validator for the frameBorder attribute but keeps css for future browsers as explained in the post.

How to resolve "Input string was not in a correct format." error?

Because Label1.Text is holding Label which can't be parsed into integer, you need to convert the associated textbox's text to integer

imageWidth = 1 * Convert.ToInt32(TextBox2.Text);

Show/Hide Multiple Divs with Jquery

Assign each div a class. Then you can perform actions on all of them:

$(".divClass").hide();

So each button can do:

$(".divClass").hide()
$("#specificDiv").show();

You can make this more generic, and use the obvious convention - the button and the div with the same number in the id are related. So:

$(".button").click(function() {
  var divId = "#div" + $(this).attr("id").replace("showdiv", "");
  $(".divClass").hide(); 
  $(divId).show();
}

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

This solution is Only for local system / localhost on windows:

The simplest way to install xampp 5.6.X version as per your requirement in other windows drive then run xampp 5.6.X services from it's control panel for php 5.6 version.

NOTE: If you already have xampp (any other version) on your system then please close that xampp's services then start xampp 5.6.x services otherwise this solution will not work.

You can download your required (xampp 5.6 as per question) xampp version from below link:

https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/

I have used this solution many times, it worked like charm. I hope this will also help you. Thank you to ask this question.

Javascript - sort array based on another array

Use intersection of two arrays.

Ex:

var sortArray = ['a', 'b', 'c',  'd', 'e'];

var arrayToBeSort = ['z', 's', 'b',  'e', 'a'];

_.intersection(sortArray, arrayToBeSort) 

=> ['a', 'b', 'e']

if 'z and 's' are out of range of first array, append it at the end of result

c# replace \" characters

Replace(@"\""", "")

You have to use double-doublequotes to escape double-quotes within a verbatim string.

How do I get a list of all the duplicate items using pandas in python?

This may not be a solution to the question, but to illustrate examples:

import pandas as pd

df = pd.DataFrame({
    'A': [1,1,3,4],
    'B': [2,2,5,6],
    'C': [3,4,7,6],
})

print(df)
df.duplicated(keep=False)
df.duplicated(['A','B'], keep=False)

The outputs:

   A  B  C
0  1  2  3
1  1  2  4
2  3  5  7
3  4  6  6

0    False
1    False
2    False
3    False
dtype: bool

0     True
1     True
2    False
3    False
dtype: bool

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

What is a quick way to force CRLF in C# / .NET?

Simple variant:

Regex.Replace(input, @"\r\n|\r|\n", "\r\n")

For better performance:

static Regex newline_pattern = new Regex(@"\r\n|\r|\n", RegexOptions.Compiled);
[...]
    newline_pattern.Replace(input, "\r\n");

MySQL my.ini location

it is there at C:\Program Files\MySQL\MySQL Server 5.5 there are various .ini files with small, medium & large names. generally medium is used or it depends on your requirement.

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

Set inputType for an EditText Programmatically?

password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);

also you have to be careful that cursor moves to the starting point of the editText after this function is called, so make sure that you move cursor to the end point again.

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.


The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_

An attempt was made to access a socket in a way forbidden by its access permissions

I had a similar issue with Docker for Windows and Hyper-V having reserved ports for its own use- in my case, it was port 3001 that couldn't be accessed.

  • The port wasn't be used by another process- running netstat -ano | findstr 3001 in an Administrator Powershell prompt showed nothing.
  • However, netsh interface ipv4 show excludedportrange protocol=tcp showed that the port was in one of the exclusion ranges.

I was able to follow the solution described in Docker for Windows issue #3171 (Unable to bind ports: Docker-for-Windows & Hyper-V excluding but not using important port ranges):

  1. Disable Hyper-V:

    dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
    
  2. After the required restarts, reserve the port you want so Hyper-V doesn't reserve it back:

    netsh int ipv4 add excludedportrange protocol=tcp startport=3001 numberofports=1
    
  3. Reenable Hyper-V:

    dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All
    

After this, I was able to start my docker container.

$http.get(...).success is not a function

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (response){

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

Detect if range is empty

This just a slight addition to @TomM's answer/ A simple function to check if your Selection's cells are empty

Public Function CheckIfSelectionIsEmpty() As Boolean
   Dim emptySelection As Boolean:emptySelection=True
   Dim cell As Range
   For Each cell In Selection
       emptySelection = emptySelection And isEmpty(cell)
       If emptySelection = False Then
          Exit For
       End If
   Next
   CheckIfSelectionIsEmpty = emptySelection
End Function

How to add a new column to an existing sheet and name it?

Use insert method from range, for example

Sub InsertColumn()
        Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        Range("C1").Value = "Loc"
End Sub

What does the "+=" operator do in Java?

Lot many people have already explained about what it is and how it can be used but apart from the obvious you can use this operator to do a lot of programming tricks like

  • XORing of all the elements in a boolean array would tell you if the array has odd number of true elements
  • If you have an array with all numbers repeating even number of times except one which repeats odd number of times you can find that by XORing all elements.
  • Swapping values without using temporary variable
  • Finding missing number in the range 1 to n
  • Basic validation of data sent over the network.

Lot many such tricks can be done using bit wise operators, interesting topic to explore.

Subset data.frame by date

The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input

class(EPL2011_12$Date)

The output should read [1] "Date". If it doesn't, you should format it as a date by inputting

EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")

Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command

EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")

Once you have it in Date format, you can use the subset command, or you can use brackets

WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]

Where do I find the Instagram media ID of a image

So the most up-voted "Better Way" is a little deprecated so here is my edit and other solutions:

Javascript + jQuery

$.ajax({
    type: 'GET',
    url: 'http://api.instagram.com/oembed?callback=&url='+Url, //You must define 'Url' for yourself
    cache: false,
    dataType: 'json',
    jsonp: false,
    success: function (data) {
       var MediaID = data.media_id;
   }
});

PHP

$your_url = "" //Input your url
$api = file_get_contents("http://api.instagram.com/oembed?callback=&url=" . your_url);      
$media_id = json_decode($api,true)['media_id'];

So, this is just an updated version of @George's code and is currently working. However, I made other solutions, and some even avoid an ajax request:


Shortcode Ajax Solution

Certain Instagram urls use a shortened url syntax. This allows the client to just use the shortcode in place of the media id if requested properly.

An example shortcode url looks like this: https://www.instagram.com/p/Y7GF-5vftL/

The Y7GF-5vftL is your shortcode for the picture.

Using Regexp:

var url = "https://www.instagram.com/p/Y7GF-5vftL/"; //Define this yourself
var Key = /p\/(.*?)\/$/.exec(url)[1];

In the same scope, Key will contain your shortcode. Now to request, let's say, a low res picture using this shortcode, you would do something like the following:

    $.ajax({
        type: "GET",
        dataType: "json",
        url: "https://api.instagram.com/v1/media/shortcode/" + Key + "?access_token=" + access_token, //Define your 'access_token'
        success: function (RawData) {
            var LowResURL = RawData.data.images.low_resolution.url;
        }
    });

There is lots of other useful information, including the media id, in the returned RawData structure. Log it or look up the api documentation to see.


Shortcode Conversion Solution

You can actually convert your shortcode to the id fairly easily! Here's a simple way to do it in javascript:

function shortcodeToInstaID(Shortcode) {
      var char;
      var id = 0;
      var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
      for (var i = 0; i < Shortcode.length; i++) {
          char = Shortcode[i];
          id = (id * 64) + alphabet.indexOf(char);
      }
      return id;
  }

Note: If you want a more robust node.js solution, or want to see how you would convert it back, check out @Slang's module on npm.


Full Page Solution

So what if you have the URL to a full Instagram page like: https://www.instagram.com/p/BAYYJBwi0Tssh605CJP2bmSuRpm_Jt7V_S8q9A0/

Well, you can actually read the HTML to find a meta property that contains the Media ID. There are also a couple other algorithms you can perform on the URL itself to get it, but I believe that requires too much effort so we will keep it simple. Either query the meta tag al:ios:url or iterate through the html. Since reading metatags is posted all over, I'll show you how to iterate.

NOTE: This is a little unstable and is vulnerable to being patched. This method does NOT work on a page that uses a preview box. So if you give it the current HTML when you click on a picture in someone's profile, this WILL break and return a bad Media ID.

function getMediaId(HTML_String) {
  var MediaID = "";
  var e = HTML_String.indexOf("al:ios:url") + 42; //HTML_String is a variable that contains all of the HTML text as a string for the current document. There are many different ways to retrieve this so look one up. 
  for (var i = e; i <= e + 100; i++) { //100 should never come close to being reached
      if (request.source.charAt(i) == "\"")
         break;
      MediaID += request.source.charAt(i);
  }
  return MediaID;
}

And there you go, a bunch of different ways to use Instagram's api to get a Media ID. Hope one fixes your struggles.

Split text file into smaller multiple text file using command line

here is one in c# that doesn't run out of memory when splitting into large chunks! I needed to split 95M file into 10M x line files.

var fileSuffix = 0;
int lines = 0;
Stream fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
StreamWriter sw = new StreamWriter(fstream);

using (var file = File.OpenRead(filename))
using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        sw.WriteLine(reader.ReadLine());
        lines++;

        if (lines >= 10000000)
        {
              sw.Close();
              fstream.Close();
              lines = 0;
              fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
              sw = new StreamWriter(fstream);
        }
    }
}

sw.Close();
fstream.Close();

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Control the dashed border stroke length and distance between strokes

There's a cool tool made by @kovart called the dashed border generator.

It uses an svg as a background image to allow setting the stroke dash array you desire, and is pretty convenient.

You would then simply use it as the background property on your element in place of the border:

div {
  background-image: url("data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' stroke='black' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e");
  padding: 20px;
  display: inline-block;
}

How do I build JSON dynamically in javascript?

First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

Can we open pdf file using UIWebView on iOS?

Yes, this can be done with the UIWebView.

If you are trying to display a PDF file residing on a server somewhere, you can simply load it in your web view directly:

Objective-C

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

NSURL *targetURL = [NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];

Swift

let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))

let targetURL = NSURL(string: "https://www.example.com/document.pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)

view.addSubview(webView)

Or if you have a PDF file bundled with your application (in this example named "document.pdf"):

Objective-C

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

NSURL *targetURL = [[NSBundle mainBundle] URLForResource:@"document" withExtension:@"pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

[self.view addSubview:webView];

Swift

let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))

let targetURL = NSBundle.mainBundle().URLForResource("document", withExtension: "pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)

view.addSubview(webView)

You can find more information here: Technical QA1630: Using UIWebView to display select document types.

How can I send an email through the UNIX mailx command?

Its faster with MUTT command

echo "Body Of the Email"  | mutt -a "File_Attachment.csv" -s "Daily Report for $(date)"  -c [email protected] [email protected] -y
  1. -c email cc list
  2. -s subject list
  3. -y to send the mail

Is there any ASCII character for <br>?

& is a character; &amp; is a HTML character entity for that character.

<br> is an element. Elements don't get character entities.

In contrast to many answers here, \n or &#13; are not equivalent to <br>. The former denotes a line break in text documents. The latter is intended to denote a line break in HTML documents and is doing that by virtue of its default CSS:

br:before { content: "\A"; white-space: pre-line }

A textual line break can be rendered as an HTML line break or can be treated as whitespace, depending on the CSS white-space property.

Windows batch command(s) to read first line from text file

The problem with the EXIT /B solutions, when more realistically inside a batch file as just one part of it is the following. There is no subsequent processing within the said batch file after the EXIT /B. Usually there is much more to batches than just the one, limited task.

To counter that problem:

@echo off & setlocal enableextensions enabledelayedexpansion
set myfile_=C:\_D\TEST\My test file.txt
set FirstLine=
for /f "delims=" %%i in ('type "%myfile_%"') do (
  if not defined FirstLine set FirstLine=%%i)
echo FirstLine=%FirstLine%
endlocal & goto :EOF

(However, the so-called poison characters will still be a problem.)

More on the subject of getting a particular line with batch commands:

How do I get the n'th, the first and the last line of a text file?" http://www.netikka.net/tsneti/info/tscmd023.htm

[Added 28-Aug-2012] One can also have:

@echo off & setlocal enableextensions
set myfile_=C:\_D\TEST\My test file.txt
for /f "tokens=* delims=" %%a in (
  'type "%myfile_%"') do (
    set FirstLine=%%a& goto _ExitForLoop)
:_ExitForLoop
echo FirstLine=%FirstLine%
endlocal & goto :EOF

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

In openCV's documentation there is an example for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in python.

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
{
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;)
    {
        Mat frame;
        cap >> frame; // get a new frame from camera
        cvtColor(frame, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
        Canny(edges, edges, 0, 30, 3);
        imshow("edges", edges);
        if(waitKey(30) >= 0) break;
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

Maven: add a dependency to a jar by relative path

This is working for me: Let's say I have this dependency

<dependency>
    <groupId>com.company.app</groupId>
    <artifactId>my-library</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/my-library.jar</systemPath>
</dependency>

Then, add the class-path for your system dependency manually like this

<Class-Path>libs/my-library-1.0.jar</Class-Path>

Full config:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <archive>
            <manifestEntries>
                <Build-Jdk>${jdk.version}</Build-Jdk>
                <Implementation-Title>${project.name}</Implementation-Title>
                <Implementation-Version>${project.version}</Implementation-Version>
                <Specification-Title>${project.name} Library</Specification-Title>
                <Specification-Version>${project.version}</Specification-Version>
                <Class-Path>libs/my-library-1.0.jar</Class-Path>
            </manifestEntries>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.company.app.MainClass</mainClass>
                <classpathPrefix>libs/</classpathPrefix>
            </manifest>
        </archive>
    </configuration>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.5.1</version>
    <executions>
        <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/libs/</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

C# winforms combobox dynamic autocomplete

Here is my final solution. It works fine with a large amount of data. I use Timer to make sure the user want find current value. It looks like complex but it doesn't. Thanks to Max Lambertini for the idea.

        private bool _canUpdate = true; 

        private bool _needUpdate = false;       

        //If text has been changed then start timer
        //If the user doesn't change text while the timer runs then start search
        private void combobox1_TextChanged(object sender, EventArgs e)
        {
            if (_needUpdate)
            {
                if (_canUpdate)
                {
                    _canUpdate = false;
                    UpdateData();                   
                }
                else
                {
                    RestartTimer();
                }
            }
        }

        private void UpdateData()
        {
            if (combobox1.Text.Length > 1)
            {
                List<string> searchData = Search.GetData(combobox1.Text);
                HandleTextChanged(searchData);
            }
        }       

        //If an item was selected don't start new search
        private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            _needUpdate = false;
        }

        //Update data only when the user (not program) change something
        private void combobox1_TextUpdate(object sender, EventArgs e)
        {
            _needUpdate = true;
        }

        //While timer is running don't start search
        //timer1.Interval = 1500;
        private void RestartTimer()
        {
            timer1.Stop();
            _canUpdate = false;
            timer1.Start();
        }

        //Update data when timer stops
        private void timer1_Tick(object sender, EventArgs e)
        {
            _canUpdate = true;
            timer1.Stop();
            UpdateData();
        }

        //Update combobox with new data
        private void HandleTextChanged(List<string> dataSource)
        {
            var text = combobox1.Text;

            if (dataSource.Count() > 0)
            {
                combobox1.DataSource = dataSource;  

                var sText = combobox1.Items[0].ToString();
                combobox1.SelectionStart = text.Length;
                combobox1.SelectionLength = sText.Length - text.Length;
                combobox1.DroppedDown = true;


                return;
            }
            else
            {
                combobox1.DroppedDown = false;
                combobox1.SelectionStart = text.Length;
            }
        }

This solution isn't very cool. So if someone has another solution please share it with me.

How can I resize an image dynamically with CSS as the browser width/height changes?

2018 and later solution:

Using viewport-relative units should make your life way easier, given we have the image of a cat:

cat

Now we want this cat inside our code, while respecting aspect ratios:

_x000D_
_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<img src="https://www.petmd.com/sites/default/files/petmd-cat-happy-10.jpg" alt="cat">
_x000D_
_x000D_
_x000D_

So far not really interesting, but what if we would like to change the cats width to be the maximum of 50% of the viewport?

_x000D_
_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
  /* Magic! */_x000D_
  max-width: 50vw;_x000D_
}
_x000D_
<img src="https://www.petmd.com/sites/default/files/petmd-cat-happy-10.jpg" alt="cat">
_x000D_
_x000D_
_x000D_

The same image, but now restricted to a maximum width of 50vw vw (=viewport width) means the image will be X width of the viewport, depending on the digit provided. This also works for height:

_x000D_
_x000D_
img {_x000D_
  width: auto;_x000D_
  height: 100%;_x000D_
  max-height: 20vh;_x000D_
}
_x000D_
<img src="https://www.petmd.com/sites/default/files/petmd-cat-happy-10.jpg" alt="cat">
_x000D_
_x000D_
_x000D_

This restricts the height of the image to a maximum of 20% of the viewport.

PHP Using RegEx to get substring of a string

<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>

How can I make git accept a self signed certificate?

I keep coming across this problem, so have written a script to download the self signed certificate from the server and install it to ~/.gitcerts, then update git-config to point to these certificates. It is stored in global config, so you only need to run it once per remote.

https://github.com/iwonbigbro/tools/blob/master/bin/git-remote-install-cert.sh

Find difference between timestamps in seconds in PostgreSQL

select age(timestamp_A, timestamp_B)

Answering to Igor's comment:

select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
              age              
-------------------------------
 1 year 1 mon 28 days 00:01:28

How To Set A JS object property name from a variable

Along the lines of Sainath S.R's comment above, I was able to set a js object property name from a variable in Google Apps Script (which does not support ES6 yet) by defining the object then defining another key/value outside of the object:

var salesperson = ...

var mailchimpInterests = { 
        "aGroupId": true,
    };

mailchimpInterests[salesperson] = true;

CSS to line break before/after a particular `inline-block` item

You are not interested in a lot of "solutions" to your problem. I do not think there really is a good way to do what you want to do. Anything you insert using :after and content has exactly the same syntactic and semantic validity it would have done if you had just written it in there yourself.

The tools CSS provide work. You should just float the lis and then clear: left when you want to start a new line, as you have mentioned:

See an example: http://jsfiddle.net/marcuswhybrow/YMN7U/5/

Save PHP variables to a text file

Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).

Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.

$file = '/tmp/file';
$content = serialize($my_variable);
file_put_contents($file, $content);
$content = unserialize(file_get_contents($file));

Update and left outer join statements

Just another example where the value of a column from table 1 is inserted into a column in table 2:

UPDATE  Address
SET     Phone1 = sp.Phone
FROM    Address ad LEFT JOIN Speaker sp
ON      sp.AddressID = ad.ID
WHERE   sp.Phone <> '' 

Query to list number of records in each table in a database

If you use MySQL >4.x you can use this:

select TABLE_NAME, TABLE_ROWS from information_schema.TABLES where TABLE_SCHEMA="test";

Keep in mind that for some storage engines, TABLE_ROWS is an approximation.

Convert DataSet to List

                DataSet ds = new DataSet();
                ds = obj.getXmlData();// get the multiple table in dataset.

                Employee objEmp = new Employee ();// create the object of class Employee 
                List<Employee > empList = new List<Employee >();
                int table = Convert.ToInt32(ds.Tables.Count);// count the number of table in dataset
                for (int i = 1; i < table; i++)// set the table value in list one by one
                {
                    foreach (DataRow dr in ds.Tables[i].Rows)
                    {
                        empList.Add(new Employee { Title1 = Convert.ToString(dr["Title"]), Hosting1 = Convert.ToString(dr["Hosting"]), Startdate1 = Convert.ToString(dr["Startdate"]), ExpDate1 = Convert.ToString(dr["ExpDate"]) });
                    }
                }
                dataGridView1.DataSource = empList;

enter image description here

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

int to unsigned int conversion

i=-62 . If you want to convert it to a unsigned representation. It would be 4294967234 for a 32 bit integer. A simple way would be to

num=-62
unsigned int n;
n = num
cout<<n;

4294967234

How do I automatically play a Youtube video (IFrame API) muted?

You can select the video player and then set its volume:

var mp = iframe.getElementById('movie_player');
mp.setVolume(0);

Source: http://userscripts.org/scripts/review/49366

How to Maximize window in chrome using webDriver (python)

I do the following:

from selenium import webdriver
browser = webdriver.Chrome('C:\chromedriver.exe')
browser.maximize_window()

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

In Python, how to display current time in readable format

import time
time.strftime('%H:%M%p %Z on %b %d, %Y')

This may come in handy

How to determine the current language of a wordpress page when using polylang?

We can use the get_locale function:

if (get_locale() == 'en_GB') {
    // drink tea
}

CORS with POSTMAN

As @Musa comments it, it seems that the reason is that:

Postman doesn't care about SOP, it's a dev tool not a browser

By the way here's a chrome extension in order to make it work on your browser (this one is for chrome, but you can find either for FF or Safari).

Check here if you want to learn more about Cross-Origin and why it's working for extensions.

Prompt Dialog in Windows Forms

The answer of Bas can get you in memorytrouble theoretically, since ShowDialog won't be disposed. I think this is a more proper way. Also mention the textLabel being readable with longer text.

public class Prompt : IDisposable
{
    private Form prompt { get; set; }
    public string Result { get; }

    public Prompt(string text, string caption)
    {
        Result = ShowDialog(text, caption);
    }
    //use a using statement
    private string ShowDialog(string text, string caption)
    {
        prompt = new Form()
        {
            Width = 500,
            Height = 150,
            FormBorderStyle = FormBorderStyle.FixedDialog,
            Text = caption,
            StartPosition = FormStartPosition.CenterScreen,
            TopMost = true
        };
        Label textLabel = new Label() { Left = 50, Top = 20, Text = text, Dock = DockStyle.Top, TextAlign = ContentAlignment.MiddleCenter };
        TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
        Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.AcceptButton = confirmation;

        return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
    }

    public void Dispose()
    {
        //See Marcus comment
        if (prompt != null) { 
            prompt.Dispose(); 
        }
    }
}

Implementation:

using(Prompt prompt = new Prompt("text", "caption")){
    string result = prompt.Result;
}

Adding input elements dynamically to form

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.

Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.

_x000D_
_x000D_
<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>
_x000D_
_x000D_
_x000D_

See a working sample in this JSFiddle.

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

Converting two lists into a matrix

The standard numpy function for what you want is np.column_stack:

>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
       [2, 5],
       [3, 6]])

So with your portfolio and index arrays, doing

np.column_stack((portfolio, index))

would yield something like:

[[portfolio_value1, index_value1],
 [portfolio_value2, index_value2],
 [portfolio_value3, index_value3],
 ...]

Is String.Contains() faster than String.IndexOf()?

Probably, it will not matter at all. Read this post on Coding Horror ;): http://www.codinghorror.com/blog/archives/001218.html

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Pass a javascript variable value into input type hidden value

You could give your hidden field an id:

<input type="hidden" id="myField" value="" />

and then when you want to assign its value:

document.getElementById('myField').value = product(2, 3);

Make sure that you are performing this assignment after the DOM has been fully loaded, for example in the window.load event.

Django DoesNotExist

This line

 except Vehicle.vehicledevice.device.DoesNotExist

means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like

 except Device.DoesNotExist

Disabling contextual LOB creation as createClob() method threw error

Update to this for using Hibernate 4.3.x / 5.0.x - you could just set this property to true:

<prop key="hibernate.jdbc.lob.non_contextual_creation">true</prop>

to get rid of that error message. Same effect but without the "threw exception" detail. See LobCreatorBuilder source for details.

Page unload event in asp.net

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        // your code
    }

But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.