Programs & Examples On #Local storage

LocalStorage is a way to store persistent data using JavaScript (see also: SessionStorage).

Local storage in Angular 2

Install "angular-2-local-storage"

import { LocalStorageService } from 'angular-2-local-storage';

Is it safe to store a JWT in localStorage with ReactJS?

It is safe to store your token in localStorage as long as you encrypt it. Below is a compressed code snippet showing one of many ways you can do it.

    import SimpleCrypto from 'simple-crypto-js';

    const saveToken = (token = '') => {
          const encryptInit = new SimpleCrypto('PRIVATE_KEY_STORED_IN_ENV_FILE');
          const encryptedToken = encryptInit.encrypt(token);

          localStorage.setItem('token', encryptedToken);
     }

Then, before using your token decrypt it using PRIVATE_KEY_STORED_IN_ENV_FILE

Get HTML5 localStorage keys

You can use the localStorage.key(index) function to return the string representation, where index is the nth object you want to retrieve.

How do I store an array in localStorage?

The JSON approach works, on ie 7 you need json2.js, with it it works perfectly and despite the one comment saying otherwise there is localStorage on it. it really seems like the best solution with the least hassle. Of course one could write scripts to do essentially the same thing as json2 does but there is little point in that.

at least with the following version string there is localStorage, but as said you need to include json2.js because that isn't included by the browser itself: 4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; BRI/2; NP06; .NET4.0C; .NET4.0E; Zune 4.7) (I would have made this a comment on the reply, but can't).

How to save to local storage using Flutter?

If you need to store just simple values like API token or login data (not passwords!), here is what I used:

import 'package:shared_preferences/shared_preferences.dart';

asyncFunc() async { // Async func to handle Futures easier; or use Future.then
  SharedPreferences prefs = await SharedPreferences.getInstance();
}
...

// Set
prefs.setString('apiToken', token);

// Get
String token = prefs.getString('apiToken');

// Remove
prefs.remove('apiToken');

Don't forget to add shared_preferences dependency in your pubspec.yaml (preserve spacing format):

dependencies:

  shared_preferences: any

Local Storage vs Cookies

Local storage can store up to 5mb offline data, whereas session can also store up to 5 mb data. But cookies can store only 4kb data in text format.

LOCAl and Session storage data in JSON format, thus easy to parse. But cookies data is in string format.

Android webview & localStorage

I've also had problem with data being lost after application is restarted. Adding this helped:

webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");

How to save an image to localStorage and display it on the next page?

I wrote a little 2,2kb library of saving image in localStorage JQueryImageCaching Usage:

<img data-src="path/to/image">
<script>
    $('img').imageCaching();
</script>

use localStorage across subdomains

I'm using xdLocalStorage, this is a lightweight js library which implements LocalStorage interface and support cross domain storage by using iframe post message communication.( angularJS support )

https://github.com/ofirdagan/cross-domain-local-storage

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

As already explained in other answers, when in Private Browsing mode Safari will always throw this exception when trying to save data with localStorage.setItem() .

To fix this I wrote a fake localStorage that mimics localStorage, both methods and events.

Fake localStorage: https://gist.github.com/engelfrost/fd707819658f72b42f55

This is probably not a good general solution to the problem. This was a good solution for my scenario, where the alternative would be major re-writes to an already existing application.

How to remove and clear all localStorage data

If you want to remove/clean all the values from local storage than use

localStorage.clear();

And if you want to remove the specific item from local storage than use the following code

localStorage.removeItem(key);

Clearing localStorage in javascript?

localStorage.clear();

or

window.localStorage.clear();

to clear particular item

window.localStorage.removeItem("item_name");

To remove particular value by id :

var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];           
            $.each(item_detail, function(index, obj){
                if (key_id == data('key')) {
                    item_detail.splice(index,1);
                    localStorage["key_name"] = JSON.stringify(item_detail);
                    return false;
                }
            });

Chrome extension: accessing localStorage in content script

Update 2016:

Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html

It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.

    // Save it using the Chrome extension storage API.
    chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
      console.log('Settings saved');
    });

    // Read it using the storage API
    chrome.storage.sync.get(['foo', 'bar'], function(items) {
      message('Settings retrieved', items);
    });

To use it, make sure you define it in the manifest:

    "permissions": [
      "storage"
    ],

There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"

Using native localStorage (old reply from 2011)

Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.

Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.

The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:

contentscript.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});

You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.

I hope that helped solve your problem.

To be fancy and generic ...

contentscript.js

chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});

Push JSON Objects to array in localStorage

Putting a whole array into one localStorage entry is very inefficient: the whole thing needs to be re-encoded every time you add something to the array or change one entry.

An alternative is to use http://rhaboo.org which stores any JS object, however deeply nested, using a separate localStorage entry for each terminal value. Arrays are restored much more faithfully, including non-numeric properties and various types of sparseness, object prototypes/constructors are restored in standard cases and the API is ludicrously simple:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);

store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});  
store.somethingfancy.went[1].mow.write(1, 'lawn');

BTW, I wrote it.

HTML5 LocalStorage: Checking if a key exists

Quoting from the specification:

The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.

You should actually check against null.

if (localStorage.getItem("username") === null) {
  //...
}

What is the difference between localStorage, sessionStorage, session and cookies?

LocalStorage:

  • Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie.

  • The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.

  • The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

  • It works on same-origin policy. So, data stored will only be available on the same origin.

Cookies:

  • We can set the expiration time for each cookie

  • The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

  • The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

sessionStorage:

  • It is similar to localStorage.
  • Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted The data is available only inside the window/tab in which it was set.

  • The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

How to view/delete local storage in Firefox?

Try this, it works for me:

var storage = null;
setLocalStorage();

function setLocalStorage() {
    storage = (localStorage ? localStorage : (window.content.localStorage ? window.content.localStorage : null));

    try {
        storage.setItem('test_key', 'test_value');//verify if posible saving in the current storage
    }
    catch (e) {
        if (e.name == "NS_ERROR_FILE_CORRUPTED") {
            storage = sessionStorage ? sessionStorage : null;//set the new storage if fails
        }
    }
}

Setting and getting localStorage with jQuery

Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.

Sample using .text()

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// alert the value to check if we got it
alert(localStorage.getItem('test'));

JSFiddle: https://jsfiddle.net/f3zLa3zc/


Storing the HTML itself

// get html
var html = $('#test')[0].outerHTML;

// set localstorage
localStorage.setItem('htmltest', html);

// test if it works
alert(localStorage.getItem('htmltest'));

JSFiddle:
https://jsfiddle.net/psfL82q3/1/


Update on user comment

A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// bind text to 'blur' event for div
$('#test').on('blur', function() {

    // check the new text
    var newText = $(this).text();

    // overwrite the old text
    localStorage.setItem('test', newText);

    // test if it works
    alert(localStorage.getItem('test'));

});

If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.

JSFiddle:
https://jsfiddle.net/g1b8m1fc/

Storing Objects in HTML5 localStorage

You can use ejson to store the objects as strings.

EJSON is an extension of JSON to support more types. It supports all JSON-safe types, as well as:

All EJSON serializations are also valid JSON. For example an object with a date and a binary buffer would be serialized in EJSON as:

{
  "d": {"$date": 1358205756553},
  "b": {"$binary": "c3VyZS4="}
}

Here is my localStorage wrapper using ejson

https://github.com/UziTech/storage.js

I added some types to my wrapper including regular expressions and functions

Add attribute 'checked' on click jquery

If .attr() isn't working for you (especially when checking and unchecking boxes in succession), use .prop() instead of .attr().

Viewing local storage contents on IE

Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:

  • Open Dev tools (F12)
  • Go to Debugger tab
  • Click the folder icon to show a list of resources - opens in a separate tab

Dev tools screenshot

What is the max size of localStorage values?

You can use the following code in modern browsers to efficiently check the storage quota (total & used) in real-time:

if ('storage' in navigator && 'estimate' in navigator.storage) {
        navigator.storage.estimate()
            .then(estimate => {
                console.log("Usage (in Bytes): ", estimate.usage,
                            ",  Total Quota (in Bytes): ", estimate.quota);
            });
}

How do I download and save a file locally on iOS using objective C?

I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:

NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
  [urlData writeToFile:filePath atomically:YES];
}

HTML5 Local storage vs. Session storage

Late answer but felt to add some points here.

Session storage will be available for specific tab where as we can use Local storage through out the browser. Both are default to same origin and we can also store values manually with key, value pairs (value must be string).

Once tab (session) of the browser is closed then Session storage will be cleared on that tab, where as in case of Local storage we need to clear it explicitly. Maximum storage limit respectively 5MB and 10MB.

We can save and retrieve the data like below,

To Save:

sessionStorage.setItem('id', noOfClicks);   // localStorage.setItem('id', noOfClicks);

sessionStorage.setItem('userDetails', JSON.stringify(userDetails));   // if it's object

To Get:

sessionStorage.getItem('id');    // localStorage.getItem('id');

User user = JSON.parse(sessionStorage.getItem("userDetails")) as User;  // if it's object

To Modify:

sessionStorage.removeItem('id');    // localStorage.removeItem('id');

sessionStorage.clear();   // localStorage.clear();

P.S: getItem() also return back the data as string and we need convert it into JSON format to access if it's object.

You can read more about Browser Storages here..

  1. Difference between localStorage, sessionStorage and cookies

  2. localstorage-vs-sessionstorage

When do items in HTML5 local storage expire?

Workaround using angular and localforage:

angular.module('app').service('cacheService', function() {

  return {
    set: function(key, value, expireTimeInSeconds) {
      return localforage.setItem(key, {
        data: value,
        timestamp: new Date().getTime(),
        expireTimeInMilliseconds: expireTimeInSeconds * 1000
      })
    },
    get: function(key) {
      return localforage.getItem(key).then(function(item) {
        if(!item || new Date().getTime() > (item.timestamp + item.expireTimeInMilliseconds)) {
          return null
        } else {
          return item.data
        }
      })
    }
  }

})

How to store token in Local or Session Storage in Angular 2?

Save to local storage

localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name }));

Load from local storage

var currentUser = JSON.parse(localStorage.getItem('currentUser'));
var token = currentUser.token; // your token

For more I suggest you go through this tutorial: Angular 2 JWT Authentication Example & Tutorial

How to check whether a Storage item is set?

localStorage['root2']=null;

localStorage.getItem("root2") === null //false

Maybe better to do a scan of the plan ?

localStorage['root1']=187;
187
'root1' in localStorage
true

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

HTML5 Pre-resize images before uploading

If you don't want to reinvent the wheel you may try plupload.com

Can local storage ever be considered secure?

No.

localStorage is accessible by any webpage, and if you have the key, you can change whatever data you want.

That being said, if you can devise a way to safely encrypt the keys, it doesn't matter how you transfer the data, if you can contain the data within a closure, then the data is (somewhat) safe.

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

I had the same problem using Ionic framework (Angular + Cordova). I know this not solve the problem, but it's the code for Angular Apps based on the answers above. You will have a ephemeral solution for localStorage on iOS version of Safari.

Here is the code:

angular.module('myApp.factories', [])
.factory('$fakeStorage', [
    function(){
        function FakeStorage() {};
        FakeStorage.prototype.setItem = function (key, value) {
            this[key] = value;
        };
        FakeStorage.prototype.getItem = function (key) {
            return typeof this[key] == 'undefined' ? null : this[key];
        }
        FakeStorage.prototype.removeItem = function (key) {
            this[key] = undefined;
        };
        FakeStorage.prototype.clear = function(){
            for (var key in this) {
                if( this.hasOwnProperty(key) )
                {
                    this.removeItem(key);
                }
            }
        };
        FakeStorage.prototype.key = function(index){
            return Object.keys(this)[index];
        };
        return new FakeStorage();
    }
])
.factory('$localstorage', [
    '$window', '$fakeStorage',
    function($window, $fakeStorage) {
        function isStorageSupported(storageName) 
        {
            var testKey = 'test',
                storage = $window[storageName];
            try
            {
                storage.setItem(testKey, '1');
                storage.removeItem(testKey);
                return true;
            } 
            catch (error) 
            {
                return false;
            }
        }
        var storage = isStorageSupported('localStorage') ? $window.localStorage : $fakeStorage;
        return {
            set: function(key, value) {
                storage.setItem(key, value);
            },
            get: function(key, defaultValue) {
                return storage.getItem(key) || defaultValue;
            },
            setObject: function(key, value) {
                storage.setItem(key, JSON.stringify(value));
            },
            getObject: function(key) {
                return JSON.parse(storage.getItem(key) || '{}');
            },
            remove: function(key){
                storage.removeItem(key);
            },
            clear: function() {
                storage.clear();
            },
            key: function(index){
                storage.key(index);
            }
        }
    }
]);

Source: https://gist.github.com/jorgecasar/61fda6590dc2bb17e871

Enjoy your coding!

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

How to delete a localStorage item when the browser window/tab is closed?

You can simply use sessionStorage. Because sessionStorage allow to clear all key value when browser window will be closed .

See there : SessionStorage- MDN

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

If you are using lodash, it could be as simple as this:

var arr = _.values(obj);

Create a unique number with javascript time

I have done this way

function uniqeId() {
   var ranDom = Math.floor(new Date().valueOf() * Math.random())
   return _.uniqueId(ranDom);
}

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

I got stuck on this error because in the class that has the @SpringBootApplication I forgot to specify the controller's package name.

I wanted to be more specific this time pointing out which components Spring had to scan, instead of configuring the base package.

It was like this:

@ComponentScan(basePackages = {"br.com.company.project.repository", "br.com.company.project.service"})

But the correct form is one of these:

@ComponentScan(basePackages = {"br.com.company.project.repository", "br.com.company.project.service", "br.com.company.project.controller"})

@ComponentScan(basePackages = {"br.com.company.project")

I decided to share my solution, because although the correct answer is very comprehensive, it doesn't cover this (idiotic) mistake :)

denied: requested access to the resource is denied : docker

rename your image to username/image-name docker tag your-current-image/current-image dockerhub-username/some-name:your-tag(example: latest)

How to properly use jsPDF library

first, you have to create a handler.

var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;
    }
};

then write this code in click event:

doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
    'elementHandlers': specialElementHandlers
        });

var pdfOutput = doc.output();
            console.log(">>>"+pdfOutput );

assuming you've already declared doc variable. And Then you have save this pdf file using File-Plugin.

Java 8 stream map on entry set

Simply translating the "old for loop way" into streams:

private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
    int subLength = prefix.length();
    return input.entrySet().stream()
            .collect(Collectors.toMap(
                   entry -> entry.getKey().substring(subLength), 
                   entry -> AttributeType.GetByName(entry.getValue())));
}

How to redirect output of an entire shell script within the script itself?

Typically we would place one of these at or near the top of the script. Scripts that parse their command lines would do the redirection after parsing.

Send stdout to a file

exec > file

with stderr

exec > file                                                                      
exec 2>&1

append both stdout and stderr to file

exec >> file
exec 2>&1

As Jonathan Leffler mentioned in his comment:

exec has two separate jobs. The first one is to replace the currently executing shell (script) with a new program. The other is changing the I/O redirections in the current shell. This is distinguished by having no argument to exec.

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

How do you transfer or export SQL Server 2005 data to Excel

You could always use ADO to write the results out to the worksheet cells from a recordset object

Find integer index of rows with NaN in pandas dataframe

I was looking for all indexes of rows with NaN values.
My working solution:

def get_nan_indexes(data_frame):
    indexes = []
    print(data_frame)
    for column in data_frame:
        index = data_frame[column].index[data_frame[column].apply(np.isnan)]
        if len(index):
            indexes.append(index[0])
    df_index = data_frame.index.values.tolist()
    return [df_index.index(i) for i in set(indexes)]

Working with time DURATION, not time of day

What I wound up doing was: Put time duration in by hand, e.g. 1 min, 03 sec. Simple but effective. It seems Excel overwrote everything else, even when I used the 'custom format' given in some answers.

window.onunload is not working properly in Chrome browser. Can any one help me?

Please try window.onbeforeunload instead for window.onunload for chrome. You can also try calling onbeforeunload from the body> tag which might work in chrome.

However, we do have a problem with unload function in chrome browser. please check

location.href does not work in chrome when called through the body/window unload event

How to check if iframe is loaded or it has a content?

You can use the iframe's load event to respond when the iframe loads.

document.querySelector('iframe').onload = function(){
    console.log('iframe loaded');
};

This won't tell you whether the correct content loaded: To check that, you can inspect the contentDocument.

document.querySelector('iframe').onload = function(){
    var iframeBody = this.contentDocument.body;
    console.log('iframe loaded, body is: ', body);
};

Checking the contentDocument won't work if the iframe src points to a different domain from where your code is running.

What are the different types of indexes, what are the benefits of each?

PostgreSQL allows partial indexes, where only rows that match a predicate are indexed. For instance, you might want to index the customer table for only those records which are active. This might look something like:

create index i on customers (id, name, whatever) where is_active is true;

If your index many columns, and you have many inactive customers, this can be a big win in terms of space (the index will be stored in fewer disk pages) and thus performance. To hit the index you need to, at a minimum, specify the predicate:

select name from customers where is_active is true;

Instagram API: How to get all user media?

See http://instagram.com/developer/endpoints/ for information on pagination. You need to subsequentially step through the result pages, each time requesting the next part with the next_url that the result specifies in the pagination object.

Command to get nth line of STDOUT

For more completeness..

ls -l | (for ((x=0;x<2;x++)) ; do read ; done ; head -n1)

Throw away lines until you get to the second, then print out the first line after that. So, it prints the 3rd line.

If it's just the second line..

ls -l | (read; head -n1)

Put as many 'read's as necessary.

Disable F5 and browser refresh using JavaScript

Use this for modern browsers:

function my_onkeydown_handler( event ) {
    switch (event.keyCode) {
        case 116 : // 'F5'
            event.preventDefault();
            event.keyCode = 0;
            window.status = "F5 disabled";
            break;
    }
}
document.addEventListener("keydown", my_onkeydown_handler);

How to set input type date's default value to today?

use moment.js to solve this issue in 2 lines, html5 date input type only accept "YYYY-MM-DD" this format. I solve my problem this way.

var today = moment().format('YYYY-MM-DD');
 $('#datePicker').val(today);

this is simplest way to solve this issue.

Notepad++ change text color?

A little late reply, but what I found in Notepad++ v7.8.6 is, on RMB (Right Mouse Button), on selection text, it gives an option called "Style token" where it shows "Using 1st/2nd/3rd/4th/5th style" to highlight the selected text in different pre-defined colors

Throwing exceptions in a PHP Try Catch block

throw $e->getMessage();

You try to throw a string

As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

What is "String args[]"? parameter in main method Java

in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.

Trigger change event <select> using jquery

Use val() to change to the value (not the text) and trigger() to manually fire the event.

The change event handler must be declared before the trigger.

Here's a sample

$('.check').change(function(){
  var data= $(this).val();
  alert(data);            
});

$('.check')
    .val('two')
    .trigger('change');

serialize/deserialize java 8 java.time with Jackson JSON mapper

For those who use Spring Boot 2.x

There is no need to do any of the above - Java 8 LocalDateTime is serialised/de-serialised out of the box. I had to do all of the above in 1.x, but with Boot 2.x, it works seamlessly.

See this reference too JSON Java 8 LocalDateTime format in Spring Boot

FloatingActionButton example with Support Library

If you already added all libraries and it still doesn't work use:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_add" 
/>

instead of:

<android.support.design.widget.FloatingActionButton
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   app:srcCompat="@drawable/ic_add"
 />

And all will work fine :)

PHP: date function to get month of the current date

as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so

echo date('n'); // "9"

JDBC connection failed, error: TCP/IP connection to host failed

The error is self explanatory:

  • Check if your SQL server is actually up and running
  • Check SQL server hostname, username and password is correct
  • Check there's no firewall rule blocking TCP connection to port 1433
  • Check the host is actually reachable

A good check I often use is to use telnet, eg on a windows command prompt run:

telnet 127.0.0.1 1433

If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem

How to set a border for an HTML div tag

In bootstrap 4, you can use border utilities like so.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style>_x000D_
  .border-5 {_x000D_
    border-width: 5px !important;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
<textarea class="border border-dark border-5">some content</textarea>
_x000D_
_x000D_
_x000D_

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

Auto line-wrapping in SVG text

Building on @Mike Gledhill's code, I've taken it a step further and added more parameters. If you have a SVG RECT and want text to wrap inside it, this may be handy:

function wraptorect(textnode, boxObject, padding, linePadding) {

    var x_pos = parseInt(boxObject.getAttribute('x')),
    y_pos = parseInt(boxObject.getAttribute('y')),
    boxwidth = parseInt(boxObject.getAttribute('width')),
    fz = parseInt(window.getComputedStyle(textnode)['font-size']);  // We use this to calculate dy for each TSPAN.

    var line_height = fz + linePadding;

// Clone the original text node to store and display the final wrapping text.

   var wrapping = textnode.cloneNode(false);        // False means any TSPANs in the textnode will be discarded
   wrapping.setAttributeNS(null, 'x', x_pos + padding);
   wrapping.setAttributeNS(null, 'y', y_pos + padding);

// Make a copy of this node and hide it to progressively draw, measure and calculate line breaks.

   var testing = wrapping.cloneNode(false);
   testing.setAttributeNS(null, 'visibility', 'hidden');  // Comment this out to debug

   var testingTSPAN = document.createElementNS(null, 'tspan');
   var testingTEXTNODE = document.createTextNode(textnode.textContent);
   testingTSPAN.appendChild(testingTEXTNODE);

   testing.appendChild(testingTSPAN);
   var tester = document.getElementsByTagName('svg')[0].appendChild(testing);

   var words = textnode.textContent.split(" ");
   var line = line2 = "";
   var linecounter = 0;
   var testwidth;

   for (var n = 0; n < words.length; n++) {

      line2 = line + words[n] + " ";
      testing.textContent = line2;
      testwidth = testing.getBBox().width;

      if ((testwidth + 2*padding) > boxwidth) {

        testingTSPAN = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
        testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
        testingTSPAN.setAttributeNS(null, 'dy', line_height);

        testingTEXTNODE = document.createTextNode(line);
        testingTSPAN.appendChild(testingTEXTNODE);
        wrapping.appendChild(testingTSPAN);

        line = words[n] + " ";
        linecounter++;
      }
      else {
        line = line2;
      }
    }

    var testingTSPAN = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
    testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
    testingTSPAN.setAttributeNS(null, 'dy', line_height);

    var testingTEXTNODE = document.createTextNode(line);
    testingTSPAN.appendChild(testingTEXTNODE);

    wrapping.appendChild(testingTSPAN);

    testing.parentNode.removeChild(testing);
    textnode.parentNode.replaceChild(wrapping,textnode);

    return linecounter;
}

document.getElementById('original').onmouseover = function () {

    var container = document.getElementById('destination');
    var numberoflines = wraptorect(this,container,20,1);
    console.log(numberoflines);  // In case you need it

};

Check if string matches pattern

regular expressions make this easy ...

[A-Z] will match exactly one character between A and Z

\d+ will match one or more digits

() group things (and also return things... but for now just think of them grouping)

+ selects 1 or more

using batch echo with special characters

the escape character ^ also did not work for me. The single quotes worked for me (using ansible scripting)

shell: echo  '{{ jobid.content }}'

output:

 {
    "changed": true,
    "cmd": "echo  '<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>'",
    "delta": "0:00:00.004943",
    "end": "2020-07-31 08:45:05.645672",
    "invocation": {
        "module_args": {
            "_raw_params": "echo  '<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>'",
            "_uses_shell": true,
            "argv": null,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "stdin_add_newline": true,
            "strip_empty_ends": true,
            "warn": true
        }
    },
    "rc": 0,
    "start": "2020-07-31 08:45:05.640729",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>",
    "stdout_lines": [
        "<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>"
    ]

PHP-FPM doesn't write to error log

I'd like to add another tip to the existing answers because they did not solve my problem.

Watch out for the following nginx directive in your php location block:

fastcgi_intercept_errors on;

Removing this line has brought an end to many hours of struggling and pulling hair.

It could be hidden in some included conf directory like /etc/nginx/default.d/php.conf in my fedora.

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

git push rejected: error: failed to push some refs

What I did to solve the problem was:

git pull origin [branch]
git push origin [branch]

Also make sure that you are pointing to the right branch by running:

git remote set-url origin [url]

What is the best way to add a value to an array in state

If you want to keep adding a new object to the array i've been using:

_methodName = (para1, para2) => {
  this.setState({
    arr: this.state.arr.concat({para1, para2})
  })
}

How can I stop python.exe from closing immediately after I get an output?

In windows, if Python is installed into the default directory (For me it is):

cd C:\Python27

You then proceed to type

"python.exe "[FULLPATH]\[name].py" 

to run your Python script in Command Prompt

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

I'd like to add that for accessibility, I think you should add focus trigger :

i.e. $("#popover").popover({ trigger: "hover focus" });

Programmatically get own phone number in iOS

At the risk of getting negative marks, I want to suggest that the highest ranking solution (currently the first response) violates the latest SDK Agreement as of Nov 5, 2009. Our application was just rejected for using it. Here's the response from Apple:

"For security reasons, iPhone OS restricts an application (including its preferences and data) to a unique location in the file system. This restriction is part of the security feature known as the application's "sandbox." The sandbox is a set of fine-grained controls limiting an application's access to files, preferences, network resources, hardware, and so on."

The device's phone number is not available within your application's container. You will need to revise your application to read only within your directory container and resubmit your binary to iTunes Connect in order for your application to be reconsidered for the App Store.

This was a real disappointment since we wanted to spare the user having to enter their own phone number.

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

Answer seems to be a little old, What I did was to use this mapper to convert a MAP

      ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

a simple Map:

          Map<String, Object> user = new HashMap<String,Object>();
            user.put( "id",  teklif.getAccount().getId() );
            user.put( "fname", teklif.getAccount().getFname());
            user.put( "lname", teklif.getAccount().getLname());
            user.put( "email", teklif.getAccount().getEmail());
            user.put( "test", null);

Use it like this for example:

      String json = mapper.writeValueAsString(user);

Get the name of a pandas DataFrame

Here is a sample function: 'df.name = file` : Sixth line in the code below

def df_list(): filename_list = current_stage_files(PATH) df_list = [] for file in filename_list: df = pd.read_csv(PATH+file) df.name = file df_list.append(df) return df_list

Install Android App Bundle on device

Use (on Linux): cd android ./gradlew assemblyRelease|assemblyDebug

An unsigned APK is generated for each case (for debug or testing)

NOTE: On Windows, replace gradle executable for gradlew.bat

The given key was not present in the dictionary. Which key?

In the general case, the answer is No.

However, you can set the debugger to break at the point where the exception is first thrown. At that time, the key which was not present will be accessible as a value in the call stack.

In Visual Studio, this option is located here:

Debug → Exceptions... → Common Language Runtime Exceptions → System.Collections.Generic

There, you can check the Thrown box.


For more specific instances where information is needed at runtime, provided your code uses IDictionary<TKey, TValue> and not tied directly to Dictionary<TKey, TValue>, you can implement your own dictionary class which provides this behavior.

Passing $_POST values with cURL

Check out this page which has an example of how to do it.

Copy files on Windows Command Line with Progress

This technet link has some good info for copying large files. I used an exchange server utility mentioned in the article which shows progress and uses non buffered copy functions internally for faster transfer.

In another scenario, I used robocopy. Robocopy GUI makes it easier to get your command line options right.

jQuery Scroll to bottom of page/iframe

If you don't care about animation, then you don't have to get the height of the element. At least in all the browsers I've tried, if you give scrollTop a number that's bigger than the maximum, it'll just scroll to the bottom. So give it the biggest number possible:

$(myScrollingElement).scrollTop(Number.MAX_SAFE_INTEGER);

If you want to scroll the page, rather than some element with a scrollbar, just make myScrollingElement equal to 'body, html'.

Since I need to do this in several places, I've written a quick and dirty jQuery function to make it more convenient, like this:

(function($) {
  $.fn.scrollToBottom = function() {
    return this.each(function (i, element) {
      $(element).scrollTop(Number.MAX_SAFE_INTEGER);
    });
  };
}(jQuery));

So I can do this when I append a buncho' stuff:

$(myScrollingElement).append(lotsOfHtml).scrollToBottom();

Make a link use POST instead of GET

Instead using javascript, you could also use a label sending a hidden form. Very simple and small solution. The label can be anywhere in your html.

_x000D_
_x000D_
<form style="display: none" action="postUrl" method="post">_x000D_
  <button type="submit" id="button_to_link"> </button>_x000D_
</form>_x000D_
<label style="text-decoration: underline" for="button_to_link">  link that posts </label>
_x000D_
_x000D_
_x000D_

JavaScript: undefined !== undefined?

var a;

typeof a === 'undefined'; // true
a === undefined; // true
typeof a === typeof undefined; // true
typeof a === typeof sdfuwehflj; // true

R: Break for loop

Well, your code is not reproducible so we will never know for sure, but this is what help('break')says:

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.

So yes, break only breaks the current loop. You can also see it in action with e.g.:

for (i in 1:10)
{
    for (j in 1:10)
    {
        for (k in 1:10)
        {
            cat(i," ",j," ",k,"\n")
            if (k ==5) break
        }   
    }
}

How to declare an ArrayList with values?

Try this!

List<String> x = new ArrayList<String>(Arrays.asList("xyz", "abc"));

It's a good practice to declare the ArrayList with interface List if you don't have to invoke the specific methods.

jwt check if token expired

// Pass in function expiration date to check token 
function checkToken(exp) {
    if (Date.now() <= exp * 1000) {
      console.log(true, 'token is not expired')
    } else { 
      console.log(false, 'token is expired') 
    }
  }

How to copy to clipboard in Vim?

On Mac OSX

  • copy selected part: visually select text(type v or V in normal mode) and type :w !pbcopy

  • copy the whole file :%w !pbcopy

  • paste from the clipboard :r !pbpaste

On most Linux Distros, you can substitute:

  • pbcopy above with xclip -i -sel c or xsel -i -b
  • pbpaste using xclip -o -sel -c or xsel -o -b
    -- Note: In case neither of these tools (xsel and xclip) are preinstalled on your distro, you can probably find them in the repos

Function that creates a timestamp in c#

You could use the DateTime.Ticks property, which is a long and universal storable, always increasing and usable on the compact framework as well. Just make sure your code isn't used after December 31st 9999 ;)

Complex CSS selector for parent of active child

Another thought occurred to me just now that could be a pure CSS solution. Display your active class as an absolutely positioned block and set its style to cover up the parent li.

a.active {
   position:absolute;
   display:block;
   width:100%;
   height:100%;
   top:0em;
   left:0em;
   background-color: whatever;
   border: whatever;
}
/* will also need to make sure the parent li is a positioned element so... */
ul.menu li {
    position:relative;
}    

For those of you who want to use javascript without jquery...

Selecting the parent is trivial. You need a getElementsByClass function of some sort, unless you can get your drupal plugin to assign the active item an ID instead of Class. The function I provided I grabbed from some other genius on SO. It works well, just keep in mind when you're debugging that the function will always return an array of nodes, not just a single node.

active_li = getElementsByClass("active","a");
active_li[0].parentNode.style.whatever="whatever";

function getElementsByClass(node,searchClass,tag) {
    var classElements = new Array();
    var els = node.getElementsByTagName(tag); // use "*" for all elements
    var elsLen = els.length;
    var pattern = new RegExp("\\b"+searchClass+"\\b");
    for (i = 0, j = 0; i < elsLen; i++) {
       if ( pattern.test(els[i].className) ) {
       classElements[j] = els[i];
       j++;
   }
}
return classElements;
}

Add a UIView above all, even the navigation bar

Note if you want add view in Full screen then only use below code

Add these extension of UIViewController

public extension UIViewController {
   internal func makeViewAsFullScreen() {
      var viewFrame:CGRect = self.view.frame
      if viewFrame.origin.y > 0 || viewFrame.origin.x > 0 {
        self.view.frame = UIScreen.main.bounds
      }
   }
}

Continue as normal adding process of subview

Now use in adding UIViewController's viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

     self.makeViewAsFullScreen()
}

How can I match on an attribute that contains a certain string?

Be aware that bobince's answer might be overly complicated if you can assume that the class name you are interested in is not a substring of another possible class name. If this is true, you can simply use substring matching via the contains function. The following will match any element whose class contains the substring 'atag':

//*[contains(@class,'atag')]

If the assumption above does not hold, a substring match will match elements you don't intend. In this case, you have to find the word boundaries. By using the space delimiters to find the class name boundaries, bobince's second answer finds the exact matches:

//*[contains(concat(' ', normalize-space(@class), ' '), ' atag ')]

This will match atag and not matag.

Is it possible to read from a InputStream with a timeout?

If your InputStream is backed by a Socket, you can set a Socket timeout (in milliseconds) using setSoTimeout. If the read() call doesn't unblock within the timeout specified, it will throw a SocketTimeoutException.

Just make sure that you call setSoTimeout on the Socket before making the read() call.

SQL Server tables: what is the difference between @, # and ##?

CREATE TABLE #t

Creates a table that is only visible on and during that CONNECTION the same user who creates another connection will not be able to see table #t from the other connection.

CREATE TABLE ##t

Creates a temporary table visible to other connections. But the table is dropped when the creating connection is ended.

How to make unicode string with python3

Literal strings are unicode by default in Python3.

Assuming that text is a bytes object, just use text.decode('utf-8')

unicode of Python2 is equivalent to str in Python3, so you can also write:

str(text, 'utf-8')

if you prefer.

Print text in Oracle SQL Developer SQL Worksheet window

The main answer left out a step for new installs where one has to open up the dbms output window.

enter image description here

Then the script I used:

dbms_output.put_line('Start');

Another script:

set serveroutput on format wrapped;
begin
    DBMS_OUTPUT.put_line('jabberwocky');
end;

Editor does not contain a main type

On reason for an Error of: "Editor does not contain a main type"

Error encountered in: Eclipse Neon

Operating System: Windows 10 Pro

When you copy your source folders over from a thumb-drive and leave out the Eclipse_Projects.metadata folder.

Other than a fresh install, you will have to make sure you merge the files from (Thrumb-drive)F:Eclipse_Projects.metadata.plugins .

These plug-ins are the bits and pieces of library code taken from the SDK when a class is created. I really all depends on what you-----import javax.swing.*;----- into your file. Because your transferring it over make sure to merge the ------Eclipse_Projects.metadata.plugins------ manually with a simple copy and paste, while accepting the skip feature for already present plugins in your Folder.

For windows 10: you can find your working folders following a similar pattern of file hierarchy.

C:Users>Mikes Laptop> workspace > .metadata > .plugins <---merge plugins here

How to use google maps without api key

Now you must have API key. You can generate that in google developer console. Here is LINK to the explanation.

How can I create database tables from XSD files?

hyperjaxb (versions 2 and 3) actually generates hibernate mapping files and related entity objects and also does a round trip test for a given XSD and sample XML file. You can capture the log output and see the DDL statements for yourself. I had to tweak them a little bit, but it gives you a basic blue print to start with.

How to set up a Web API controller for multipart/form-data

This is what solved my problem
Add the following line to WebApiConfig.cs

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

How to pass objects to functions in C++?

Since no one mentioned I am adding on it, When you pass a object to a function in c++ the default copy constructor of the object is called if you dont have one which creates a clone of the object and then pass it to the method, so when you change the object values that will reflect on the copy of the object instead of the original object, that is the problem in c++, So if you make all the class attributes to be pointers, then the copy constructors will copy the addresses of the pointer attributes , so when the method invocations on the object which manipulates the values stored in pointer attributes addresses, the changes also reflect in the original object which is passed as a parameter, so this can behave same a Java but dont forget that all your class attributes must be pointers, also you should change the values of pointers, will be much clear with code explanation.

Class CPlusPlusJavaFunctionality {
    public:
       CPlusPlusJavaFunctionality(){
         attribute = new int;
         *attribute = value;
       }

       void setValue(int value){
           *attribute = value;
       }

       void getValue(){
          return *attribute;
       }

       ~ CPlusPlusJavaFuncitonality(){
          delete(attribute);
       }

    private:
       int *attribute;
}

void changeObjectAttribute(CPlusPlusJavaFunctionality obj, int value){
   int* prt = obj.attribute;
   *ptr = value;
}

int main(){

   CPlusPlusJavaFunctionality obj;

   obj.setValue(10);

   cout<< obj.getValue();  //output: 10

   changeObjectAttribute(obj, 15);

   cout<< obj.getValue();  //output: 15
}

But this is not good idea as you will be ending up writing lot of code involving with pointers, which are prone for memory leaks and do not forget to call destructors. And to avoid this c++ have copy constructors where you will create new memory when the objects containing pointers are passed to function arguments which will stop manipulating other objects data, Java does pass by value and value is reference, so it do not require copy constructors.

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Implicit Wait: During Implicit wait if the Web Driver cannot find it immediately because of its availability, the WebDriver will wait for mentioned time and it will not try to find the element again during the specified time period. Once the specified time is over, it will try to search the element once again the last time before throwing exception. The default setting is zero. Once we set a time, the Web Driver waits for the period of the WebDriver object instance.

Explicit Wait: There can be instance when a particular element takes more than a minute to load. In that case you definitely not like to set a huge time to Implicit wait, as if you do this your browser will going to wait for the same time for every element. To avoid that situation you can simply put a separate time on the required element only. By following this your browser implicit wait time would be short for every element and it would be large for specific element.

error::make_unique is not a member of ‘std’

In my case I was needed update the std=c++

I mean in my gradle file was this

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11", "-Wall"
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

I changed this line

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++17", "-Wall"   <-- this number from 11 to 17 (or 14)
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

That's it...

Response Content type as CSV

Use text/csv as the content type.

How to parse a string into a nullable int

Try this:

public static int? ParseNullableInt(this string value)
{
    int intValue;
    if (int.TryParse(value, out intValue))
        return intValue;
    return null;
}

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

How to scroll to an element?

You can use something like componentDidUpdate

componentDidUpdate() {
  var elem = testNode //your ref to the element say testNode in your case; 
  elem.scrollTop = elem.scrollHeight;
};

Unsigned values in C

Having unsigned in variable declaration is more useful for the programmers themselves - don't treat the variables as negative. As you've noticed, both -1 and 4294967295 have exact same bit representation for a 4 byte integer. It's all about how you want to treat or see them.

The statement unsigned int a = -1; is converting -1 in two's complement and assigning the bit representation in a. The printf() specifier x, d and u are showing how the bit representation stored in variable a looks like in different format.

What are the differences between the urllib, urllib2, urllib3 and requests module?

I like the urllib.urlencode function, and it doesn't appear to exist in urllib2.

>>> urllib.urlencode({'abc':'d f', 'def': '-!2'})
'abc=d+f&def=-%212'

What's the difference between Perl's backticks, system, and exec?

In general I use system, open, IPC::Open2, or IPC::Open3 depending on what I want to do. The qx// operator, while simple, is too constraining in its functionality to be very useful outside of quick hacks. I find open to much handier.

system: run a command and wait for it to return

Use system when you want to run a command, don't care about its output, and don't want the Perl script to do anything until the command finishes.

#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");

or

#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
#output
system("command arg1 arg2 arg3");

qx// or ``: run a command and capture its STDOUT

Use qx// when you want to run a command, capture what it writes to STDOUT, and don't want the Perl script to do anything until the command finishes.

#arguments are always processed by the shell

#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;

#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;

exec: replace the current process with another process.

Use exec along with fork when you want to run a command, don't care about its output, and don't want to wait for it to return. system is really just

sub my_system {
    die "could not fork\n" unless defined(my $pid = fork);
    return waitpid $pid, 0 if $pid; #parent waits for child
    exec @_; #replace child with new process
}

You may also want to read the waitpid and perlipc manuals.

open: run a process and create a pipe to its STDIN or STDERR

Use open when you want to write data to a process's STDIN or read data from a process's STDOUT (but not both at the same time).

#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
    or die "could not open $filename: $!";

#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
    or die "could not open $filename: $!";

IPC::Open2: run a process and create a pipe to both STDIN and STDOUT

Use IPC::Open2 when you need to read from and write to a process's STDIN and STDOUT.

use IPC::Open2;

open2 my $out, my $in, "/usr/bin/bc"
    or die "could not run bc";

print $in "5+6\n";

my $answer = <$out>;

IPC::Open3: run a process and create a pipe to STDIN, STDOUT, and STDERR

use IPC::Open3 when you need to capture all three standard file handles of the process. I would write an example, but it works mostly the same way IPC::Open2 does, but with a slightly different order to the arguments and a third file handle.

Redirecting to authentication dialog - "An error occurred. Please try again later"

I was getting this error because I was starting from http://mysite.com, but had specified http://WWW.mysite.com in my Facebook settings - the www mattered... I ended up solving by using .httpaccess to always kill the "www", and pointing FB to http://mysite.com

worst. subdomain. ever. :u)

Browser Caching of CSS files

Unless you've messed with your server, yes it's cached. All the browsers are supposed to handle it the same. Some people (like me) might have their browsers configured so that it doesn't cache any files though. Closing the browser doesn't invalidate the file in the cache. Changing the file on the server should cause a refresh of the file however.

How to capture the android device screen content?

Framebuffer seems the way to go, it will not always contain 2+ frames like mentioned by Ryan Conrad. In my case it contained only one. I guess it depends on the frame/display size.

I tried to read the framebuffer continuously but it seems to return for a fixed amount of bytes read. In my case that is (3 410 432) bytes, which is enough to store a display frame of 854*480 RGBA (3 279 360 bytes). Yes, the frame in binary outputed from fb0 is RGBA in my device. This will most likely depend from device to device. This will be important for you to decode it =)

In my device /dev/graphics/fb0 permissions are so that only root and users from group graphics can read the fb0. graphics is a restricted group so you will probably only access fb0 with a rooted phone using su command.

Android apps have the user id (uid) app_## and group id (guid) app_## .

adb shell has uid shell and guid shell, which has much more permissions than an app. You can actually check those permissions at /system/permissions/platform.xml

This means you will be able to read fb0 in the adb shell without root but you will not read it within the app without root.

Also, giving READ_FRAME_BUFFER and/or ACCESS_SURFACE_FLINGER permissions on AndroidManifest.xml will do nothing for a regular app because these will only work for 'signature' apps.

align divs to the bottom of their container

Why can't you use absolute positioning? Vertical-align does not work (except for tables). Make your container's position: relative. Then absolutely position the internal divs using bottom: 0; Should work like a charm.

EDIT By zoidberg (i will update the answer instead)

<div style="position:relative; border: 1px solid red;width: 40px; height: 40px;">
   <div style="border:1px solid green;position: absolute; bottom: 0; left: 0; width: 20px; height: 20px;"></div>
   <div style="border:1px solid blue;position: absolute; bottom: 0; left: 20px; width: 20px height: 20px;"></div>
</div>

Multiple INSERT statements vs. single INSERT with multiple VALUES

I ran into a similar situation trying to convert a table with several 100k rows with a C++ program (MFC/ODBC).

Since this operation took a very long time, I figured bundling multiple inserts into one (up to 1000 due to MSSQL limitations). My guess that a lot of single insert statements would create an overhead similar to what is described here.

However, it turns out that the conversion took actually quite a bit longer:

        Method 1       Method 2     Method 3 
        Single Insert  Multi Insert Joined Inserts
Rows    1000           1000         1000
Insert  390 ms         765 ms       270 ms
per Row 0.390 ms       0.765 ms     0.27 ms

So, 1000 single calls to CDatabase::ExecuteSql each with a single INSERT statement (method 1) are roughly twice as fast as a single call to CDatabase::ExecuteSql with a multi-line INSERT statement with 1000 value tuples (method 2).

Update: So, the next thing I tried was to bundle 1000 separate INSERT statements into a single string and have the server execute that (method 3). It turns out this is even a bit faster than method 1.

Edit: I am using Microsoft SQL Server Express Edition (64-bit) v10.0.2531.0

C# Debug - cannot start debugging because the debug target is missing

Please try with the steps below:

  1. Right click on the Visual Studio Project - Properties - Debug - (Start Action section) - select "Start project" radio button.
  2. Right click on the Visual Studio Project - Properties - Debug - (Enable Debuggers section) - mark "Enable the Visual Studio hosting process"
  3. Save changes Ctrl + Shift + S) and run the project again.

P.S. I experienced the same problem when I was playing with the options to redirect the console input / output to text file and have selected the option Properties - Debug - (Start Action section) - Start external program. When I moved the Solution to another location on my computer the problem occurred because it was searching for an absolute path to the executable file. Restoring the Visual Studio Project default settings (see above) fixed the problem. For your reference I am using Visual Studio 2013 Professional.

How do you clear the focus in javascript?

document.activeElement.blur();

Works wrong on IE9 - it blurs the whole browser window if active element is document body. Better to check for this case:

if (document.activeElement != document.body) document.activeElement.blur();

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

If you still have problem then please try this.

Build Settings -> User Defined -> Provisioning profile (Remove this.)

It will solved my issue.

Thanks

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

Following worked for me -

1) In Package.json add this:

"scripts": {
    "dev": "webpack-dev-server --progress --colors"
}

2) In webpack.config.js add this under config object that you export:

devServer: {
    host: "GACDTL001SS369k", // Your Computer Name
    port: 8080
}

3) Now on terminal type: npm run dev

4) After #3 compiles and ready just head over to your browser and key in address as http://GACDTL001SS369k:8080/

Your app should hopefully be working now with an external URL which others can access on the same network.

PS: GACDTL001SS369k was my Computer Name so do replace with whatever is yours on your machine.

CSS Box Shadow Bottom Only

You can use two elements, one inside the other, and give the outer one overflow: hidden and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"

#outer {
    width: 100px;
    overflow: hidden;
    padding-bottom: 10px;
}

#outer > div {
    width: 100px;
    height: 100px;
    background: orange;

    -moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}

Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/

Jquery function BEFORE form submission

You can use some div or span instead of button and then on click call some function which submits form at he end.

<form id="my_form">
   <span onclick="submit()">submit</span>
</form>

<script>
   function submit()
   {   
       //do something
       $("#my_form").submit();
   }
</script>

JavaScriptSerializer - JSON serialization of enum as string

Just in case anybody finds the above insufficient, I ended up settling with this overload:

JsonConvert.SerializeObject(objToSerialize, Formatting.Indented, new Newtonsoft.Json.Converters.StringEnumConverter())

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

Home does not contain an export named Home

This is the solution:

  • Go to your file Home.js
  • Make sure you export your file like this in the end of the file:
export default Home;

How to use 'hover' in CSS

The href is a required attribute of an anchor element, so without it, you cannot expect all browsers to handle it equally. Anyway, I read somewhere in a comment that you only want the link to be underlined when hovering, and not otherwise. You can use the following to achieve this, and it will only apply to links with the hover-class:

<a class="hover" href="">click</a>

a.hover {
    text-decoration: none;
}

a.hover:hover {
    text-decoration:underline;
}

Why does .json() return a promise?

Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:

if the handler function:

  • returns a value, the promise returned by then gets resolved with the returned value as its value;
  • throws an error, the promise returned by then gets rejected with the thrown error as its value;
  • returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
  • returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
  • returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Access multiple elements of list knowing their index

You can use operator.itemgetter:

from operator import itemgetter 
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)

Or you can use numpy:

import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]

But really, your current solution is fine. It's probably the neatest out of all of them.

How can I get the current stack trace in Java?

You can use Thread.currentThread().getStackTrace().

That returns an array of StackTraceElements that represent the current stack trace of a program.

Call a python function from jinja2

I like @AJP's answer. I used it verbatim until I ended up with a lot of functions. Then I switched to a Python function decorator.

from jinja2 import Template

template = '''
Hi, my name is {{ custom_function1(first_name) }}
My name is {{ custom_function2(first_name) }}
My name is {{ custom_function3(first_name) }}
'''
jinga_html_template = Template(template)

def template_function(func):
    jinga_html_template.globals[func.__name__] = func
    return func

@template_function
def custom_function1(a):
    return a.replace('o', 'ay')

@template_function
def custom_function2(a):
    return a.replace('o', 'ill')

@template_function
def custom_function3(a):
    return 'Slim Shady'

fields = {'first_name': 'Jo'}
print(jinga_html_template.render(**fields))

Good thing functions have a __name__!

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Using OR in SQLAlchemy

SQLAlchemy overloads the bitwise operators &, | and ~ so instead of the ugly and hard-to-read prefix syntax with or_() and and_() (like in Bastien's answer) you can use these operators:

.filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))

Note that the parentheses are not optional due to the precedence of the bitwise operators.

So your whole query could look like this:

addr = session.query(AddressBook) \
    .filter(AddressBook.city == "boston") \
    .filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))

CSS horizontal centering of a fixed div?

Here's another two-div solution. Tried to keep it concise and not hardcoded. First, the expectable html:

<div id="outer">
  <div id="inner">
    content
  </div>
</div>

The principle behind the following css is to position some side of "outer", then use the fact that it assumes the size of "inner" to relatively shift the latter.

#outer {
  position: fixed;
  left: 50%;          // % of window
}
#inner {
  position: relative;
  left: -50%;         // % of outer (which auto-matches inner width)
}

This approach is similar to Quentin's, but inner can be of variable size.

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

Hope this helps you in getting the exact time between two time stamps

Create PROC TimeDurationbetween2times(@iTime as time,@oTime as time) 
As  
Begin  

DECLARE @Dh int, @Dm int, @Ds int ,@Im int, @Om int, @Is int,@Os int     

SET @Im=DATEPART(MI,@iTime)  
SET @Om=DATEPART(MI,@oTime)  
SET @Is=DATEPART(SS,@iTime)  
SET @Os=DATEPART(SS,@oTime)  

SET @Dh=DATEDIFF(hh,@iTime,@oTime)  
SET @Dm = DATEDIFF(mi,@iTime,@oTime)  
SET @Ds = DATEDIFF(ss,@iTime,@oTime)  

DECLARE @HH as int, @MI as int, @SS as int  

if(@Im>@Om)  
begin  
SET @Dh=@Dh-1  
end  
if(@Is>@Os)  
begin  
SET @Dm=@Dm-1  
end  

SET @HH = @Dh  
SET @MI = @Dm-(60*@HH)  
SET @SS = @Ds-(60*@Dm)  

DECLARE @hrsWkd as varchar(8)         

SET @hrsWkd = cast(@HH as char(2))+':'+cast(@MI as char(2))+':'+cast(@SS as char(2))          

select @hrsWkd as TimeDuration   

End

How to print register values in GDB?

p $eax works as of GDB 7.7.1

As of GDB 7.7.1, the command you've tried works:

set $eax = 0
p $eax
# $1 = 0
set $eax = 1
p $eax
# $2 = 1

This syntax can also be used to select between different union members e.g. for ARM floating point registers that can be either floating point or integers:

p $s0.f
p $s0.u

From the docs:

Any name preceded by ‘$’ can be used for a convenience variable, unless it is one of the predefined machine-specific register names.

and:

You can refer to machine register contents, in expressions, as variables with names starting with ‘$’. The names of registers are different for each machine; use info registers to see the names used on your machine.

But I haven't had much luck with control registers so far: OSDev 2012 http://f.osdev.org/viewtopic.php?f=1&t=25968 || 2005 feature request https://www.sourceware.org/ml/gdb/2005-03/msg00158.html || alt.lang.asm 2013 https://groups.google.com/forum/#!topic/alt.lang.asm/JC7YS3Wu31I

ARM floating point registers

See: https://reverseengineering.stackexchange.com/questions/8992/floating-point-registers-on-arm/20623#20623

How can I change property names when serializing with Json.net?

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

What is the Angular equivalent to an AngularJS $watch?

You can use getter function or get accessor to act as watch on angular 2.

See demo here.

import {Component} from 'angular2/core';

@Component({
  // Declare the tag name in index.html to where the component attaches
  selector: 'hello-world',

  // Location of the template for this component
  template: `
  <button (click)="OnPushArray1()">Push 1</button>
  <div>
    I'm array 1 {{ array1 | json }}
  </div>
  <button (click)="OnPushArray2()">Push 2</button>
  <div>
    I'm array 2 {{ array2 | json }}
  </div>
  I'm concatenated {{ concatenatedArray | json }}
  <div>
    I'm length of two arrays {{ arrayLength | json }}
  </div>`
})
export class HelloWorld {
    array1: any[] = [];
    array2: any[] = [];

    get concatenatedArray(): any[] {
      return this.array1.concat(this.array2);
    }

    get arrayLength(): number {
      return this.concatenatedArray.length;
    }

    OnPushArray1() {
        this.array1.push(this.array1.length);
    }

    OnPushArray2() {
        this.array2.push(this.array2.length);
    }
}

Fragments within Fragments

Nested fragments are supported in android 4.2 and later

The Android Support Library also now supports nested fragments, so you can implement nested fragment designs on Android 1.6 and higher.

To nest a fragment, simply call getChildFragmentManager() on the Fragment in which you want to add a fragment. This returns a FragmentManager that you can use like you normally do from the top-level activity to create fragment transactions. For example, here’s some code that adds a fragment from within an existing Fragment class:

Fragment videoFragment = new VideoPlayerFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.video_fragment, videoFragment).commit();

To get more idea about nested fragments, please go through these tutorials
Part 1
Part 2
Part 3

and here is a SO post which discuss about best practices for nested fragments.

Plotting multiple time series on the same plot using ggplot()

This is old, just update new tidyverse workflow not mentioned above.

library(tidyverse)

jobsAFAM1 <- tibble(
    date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
    Percent.Change = runif(5, 0,1)
    ) %>% 
    mutate(serial='jobsAFAM1')
jobsAFAM2 <- tibble(
    date = seq.Date(from = as.Date('2017-01-01'),by = 'day', length.out = 5),
    Percent.Change = runif(5, 0,1)
    ) %>% 
    mutate(serial='jobsAFAM2')
jobsAFAM <- bind_rows(jobsAFAM1, jobsAFAM2)

ggplot(jobsAFAM, aes(x=date, y=Percent.Change, col=serial)) + geom_line()

@Chris Njuguna

tidyr::gather() is the one in tidyverse workflow to turn wide dataframe to long tidy layout, then ggplot could plot multiple serials.

gather

Output single character in C

Be careful of difference between 'c' and "c"

'c' is a char suitable for formatting with %c

"c" is a char* pointing to a memory block with a length of 2 (with the null terminator).

How to pass in parameters when use resource service?

I think I see your problem, you need to use the @ syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?

This is what I can suggest based on what I see so far:

.factory('MagComments', function ($resource) {
    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId'
    });
  })

The @magId string will tell the resource to replace :id with the property magId on the object you pass it as parameters.

I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

It seems you are connecting to the wrong database. R u sure "jdbc:postgresql://localhost/testDB" will connect you to the actual datasource ?

Generally they are of the form "jdbc://hostname/databasename". Look into Postgresql log file.

Counting words in string

Here's a function that counts number of words in an HTML code:

$(this).val()
    .replace(/((&nbsp;)|(<[^>]*>))+/g, '') // remove html spaces and tags
    .replace(/\s+/g, ' ') // merge multiple spaces into one
    .trim() // trim ending and beginning spaces (yes, this is needed)
    .match(/\s/g) // find all spaces by regex
    .length // get amount of matches

Can't connect to MySQL server on 'localhost' (10061)

You'll probably have to grant 'localhost' privileges to on the table to the user. See the 'GRANT' syntax documentation. Here's an example (from some C source).

"GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' IDENTIFIED BY '%s'";

That's the most common access problem with MySQL.

Other than that, you might check that the user you have defined to create your instance has full privileges, else the user cannot grant privileges.

Also, make sure the mysql service is started.

Make sure you don't have a third party firewall or Internet security service turned on.

Beyond that, there's several pages of the MySQL forum devoted to this: http://forums.mysql.com/read.php?11,9293,9609#msg-9609

Try reading that.

How to iterate over the file in python

You should learn about EAFP vs LBYL.

from sys import stdin, stdout
def main(infile=stdin, outfile=stdout):
    if isinstance(infile, basestring):
        infile=open(infile,'r')
    if isinstance(outfile, basestring):
        outfile=open(outfile,'w')
    for lineno, line in enumerate(infile, 1):
        line = line.strip()
         try:
             print >>outfile, int(line,16)
         except ValueError:
             return "Bad value at line %i: %r" % (lineno, line)

if __name__ == "__main__":
    from sys import argv, exit
    exit(main(*argv[1:]))

Is it possible to use jQuery .on and hover?

(Look at the last edit in this answer if you need to use .on() with elements populated with JavaScript)

Use this for elements that are not populated using JavaScript:

$(".selector").on("mouseover", function () {
    //stuff to do on mouseover
});

.hover() has it's own handler: http://api.jquery.com/hover/

If you want to do multiple things, chain them in the .on() handler like so:

$(".selector").on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
});

According to the answers provided below you can use hover with .on(), but:

Although strongly discouraged for new code, you may see the pseudo-event-name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

Also, there are no performance advantages to using it and it's more bulky than just using mouseenter or mouseleave. The answer I provided requires less code and is the proper way to achieve something like this.

EDIT

It's been a while since this question was answered and it seems to have gained some traction. The above code still stands, but I did want to add something to my original answer.

While I prefer using mouseenter and mouseleave (helps me understand whats going on in the code) with .on() it is just the same as writing the following with hover()

$(".selector").hover(function () {
    //stuff to do on mouse enter
}, 
function () {
    //stuff to do on mouse leave
});

Since the original question did ask how they could properly use on() with hover(), I thought I would correct the usage of on() and didn't find it necessary to add the hover() code at the time.

EDIT DECEMBER 11, 2012

Some new answers provided below detail how .on() should work if the div in question is populated using JavaScript. For example, let's say you populate a div using jQuery's .load() event, like so:

(function ($) {
    //append div to document body
    $('<div class="selector">Test</div>').appendTo(document.body);
}(jQuery));

The above code for .on() would not stand. Instead, you should modify your code slightly, like this:

$(document).on({
    mouseenter: function () {
        //stuff to do on mouse enter
    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
}, ".selector"); //pass the element as an argument to .on

This code will work for an element populated with JavaScript after a .load() event has happened. Just change your argument to the appropriate selector.

ECMAScript 6 class destructor

If there is no such mechanism, what is a pattern/convention for such problems?

The term 'cleanup' might be more appropriate, but will use 'destructor' to match OP

Suppose you write some javascript entirely with 'function's and 'var's. Then you can use the pattern of writing all the functions code within the framework of a try/catch/finally lattice. Within finally perform the destruction code.

Instead of the C++ style of writing object classes with unspecified lifetimes, and then specifying the lifetime by arbitrary scopes and the implicit call to ~() at scope end (~() is destructor in C++), in this javascript pattern the object is the function, the scope is exactly the function scope, and the destructor is the finally block.

If you are now thinking this pattern is inherently flawed because try/catch/finally doesn't encompass asynchronous execution which is essential to javascript, then you are correct. Fortunately, since 2018 the asynchronous programming helper object Promise has had a prototype function finally added to the already existing resolve and catch prototype functions. That means that that asynchronous scopes requiring destructors can be written with a Promise object, using finally as the destructor. Furthermore you can use try/catch/finally in an async function calling Promises with or without await, but must be aware that Promises called without await will be execute asynchronously outside the scope and so handle the desctructor code in a final then.

In the following code PromiseA and PromiseB are some legacy API level promises which don't have finally function arguments specified. PromiseC DOES have a finally argument defined.

async function afunc(a,b){
    try {
        function resolveB(r){ ... }
        function catchB(e){ ... }
        function cleanupB(){ ... }
        function resolveC(r){ ... }
        function catchC(e){ ... }
        function cleanupC(){ ... }
        ...
        // PromiseA preced by await sp will finish before finally block.  
        // If no rush then safe to handle PromiseA cleanup in finally block 
        var x = await PromiseA(a);
        // PromiseB,PromiseC not preceded by await - will execute asynchronously
        // so might finish after finally block so we must provide 
        // explicit cleanup (if necessary)
        PromiseB(b).then(resolveB,catchB).then(cleanupB,cleanupB);
        PromiseC(c).then(resolveC,catchC,cleanupC);
    }
    catch(e) { ... }
    finally { /* scope destructor/cleanup code here */ }
}

I am not advocating that every object in javascript be written as a function. Instead, consider the case where you have a scope identified which really 'wants' a destructor to be called at its end of life. Formulate that scope as a function object, using the pattern's finally block (or finally function in the case of an asynchronous scope) as the destructor. It is quite like likely that formulating that functional object obviated the need for a non-function class which would otherwise have been written - no extra code was required, aligning scope and class might even be cleaner.

Note: As others have written, we should not confuse destructors and garbage collection. As it happens C++ destructors are often or mainly concerned with manual garbage collection, but not exclusively so. Javascript has no need for manual garbage collection, but asynchronous scope end-of-life is often a place for (de)registering event listeners, etc..

What's "P=NP?", and why is it such a famous question?

A short summary from my humble knowledge:

There are some easy computational problems (like finding the shortest path between two points in a graph), which can be calculated pretty fast ( O(n^k), where n is the size of the input and k is a constant (in the case of graphs, it's the number of vertexes or edges)).

Other problems, like finding a path that crosses every vertex in a graph or getting the RSA private key from the public key is harder (O(e^n)).

But CS speak tells that the problem is that we cannot 'convert' a non-deterministic Turing-machine to a deterministic one, we can, however, transform non-deterministic finite automatons (like the regex parser) into deterministic ones (well, you can, but the run-time of the machine will take long). That is, we have to try every possible path (usually smart CS professors can exclude a few ones).

It's interesting because nobody even has any idea of the solution. Some say it's true, some say it's false, but there is no consensus. Another interesting thing is that a solution would be harmful for public/private key encryptions (like RSA). You could break them as easily as generating an RSA key is now.

And it's a pretty inspiring problem.

Bitbucket git credentials if signed up with Google

you don't have a bitbucket password because you log with google, but you can "reset" the password here https://bitbucket.org/account/password/reset/

you will receive an email to setup a new password and that's it.

Pass request headers in a jQuery AJAX GET call

Use beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

http://api.jquery.com/jQuery.ajax/

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

How to dynamic filter options of <select > with jQuery?

Update Lessan's answer to also keep the attributes of the options.

This is my first time answering on Stack Overflow so not sure if I should edit his answer or create my own.

jQuery.fn.allAttr = function() {
  var a, aLength, attributes, map;
  if (!this[0]) return null;
  if (arguments.length === 0) {
    map = {};
    attributes = this[0].attributes;
    aLength = attributes.length;
    for (a = 0; a < aLength; a++) {
      map[attributes[a].name.toLowerCase()] = attributes[a].value;
    }
    return map;
  } else {
    for (var propin arguments[0]) {
      $(this[0]).attr(prop, arguments[0][prop]);
    }
    return this[0];
  }
};


jQuery.fn.filterByText = function(textbox) {
  return this.each(function() {
    var select = this;
    var options = [];
    $(select).find('option').each(function() {
      options.push({ value: $(this).val(), 
        text: $(this).text(), 
        allAttr: $(this).allAttr() });
    });
    $(select).data('options', options);

    $(textbox).bind('change keyup', function() {
      var search = $.trim($(this).val());
      var regex = new RegExp(search, "gi");

      $.each($(select).empty().data('options'), function(i, option) {
        if (option.text.match(regex) !== null) {
          $(select).append(
            $('<option>').text(option.text)
            .val(option.value)
            .allAttr(option.allAttr)
          );
        }
      });
    });
  });
};

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

Start your XAMPP server by using:

  • {XAMPP}\xampp-control.exe
  • {XAMPP}\apache_start.bat

Then you have to use the URI http://localhost/index.html because htdocs is the document root of the Apache server.

If you're getting redirected to http://localhost/xampp/*, then index.php located in the htdocs folder is the problem because index.php files have a higher priority than index.html files. You could temporarily rename index.php.

The entity name must immediately follow the '&' in the entity reference

Just in case someone from Blogger arrives, I had this problem when using Beautify extension in VSCode. Don´t use it, don´t beautify it.

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

Do not use ABSOLUTE PATH to refer to the name of the image for example: C:/xamp/www/Archivos/images/templatemo_image_02_opt_20160401-1244.jpg. You must use the reference to its location within webserver. For example using ../../Archivos/images/templatemo_image_02_opt_20160401-1244.jpg depending on where your process is running.

How to create an array of 20 random bytes?

If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom.

Java 6 & 7:

SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

Java 8 (even more secure):

byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);

SQL Current month/ year question

This should work for SQL Server:

SELECT * FROM myTable
WHERE month = DATEPART(m, GETDATE()) AND
year = DATEPART(yyyy, GETDATE())

Installing a local module using npm?

So I had a lot of problems with all of the solutions mentioned so far...

I have a local package that I want to always reference (rather than npm link) because it won't be used outside of this project (for now) and also won't be uploaded to an npm repository for wide use as of yet.

I also need it to work on Windows AND Unix, so sym-links aren't ideal.

Pointing to the tar.gz result of (npm package) works for the dependent npm package folder, however this causes issues with the npm cache if you want to update the package. It doesn't always pull in the new one from the referenced npm package when you update it, even if you blow away node_modules and re-do your npm-install for your main project.

so.. This is what worked well for me!

Main Project's Package.json File Snippet:

  "name": "main-project-name",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    ...
    "preinstall": "cd ../some-npm-package-angular && npm install && npm run build"
  },
  "private": true,
  "dependencies": {
    ...
    "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist",
    ...
  }

This achieves 3 things:

  • Avoids the common error (at least with angular npm projects) "index.ts is not part of the compilation." - as it points to the built (dist) folder.
  • Adds a preinstall step to build the referenced npm client package to make sure the dist folder of our dependent package is built.
  • Avoids issues where referencing a tar.gz file locally may be cached by npm and not updated in the main project without lots of cleaning/troubleshooting/re-building/re-installing.

I hope this is clear, and helps someone out.

The tar.gz approach also sort of works..

npm install (file path) also sort of works.

This was all based off of a generated client from an openapi spec that we wanted to keep in a separate location (rather than using copy-pasta for individual files)

====== UPDATE: ======

There are additional errors with a regular development flow with the above solution, as npm's versioning scheme with local files is absolutely terrible. If your dependent package changes frequently, this whole scheme breaks because npm will cache your last version of the project and then blow up when the SHA hash doesn't match anymore with what was saved in your package-lock.json file, among other issues.

As a result, I recommend using the *.tgz approach with a version update for each change. This works by doing three things.

First:

For your dependent package, use the npm library "ng-packagr". This is automatically added to auto-generated client packages created by the angular-typescript code generator for OpenAPI 3.0.

As a result the project that I'm referencing has a "scripts" section within package.json that looks like this:

  "scripts": {
    "build": "ng-packagr -p ng-package.json",
    "package": "npm install && npm run build && cd dist && npm pack"
  },

And the project referencing this other project adds a pre-install step to make sure the dependent project is up to date and rebuilt before building itself:

  "scripts": {
    "preinstall": "npm run clean && cd ../some-npm-package-angular && npm run package"
  },

Second

Reference the built tgz npm package from your main project!

  "dependencies": {
    "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-<packageVersion>.tgz",
    ...
  }

Third

Update the dependent package's version EVERY TIME you update the dependent package. You'll also have to update the version in the main project.

If you do not do this, NPM will choke and use a cached version and explode when the SHA hash doesn't match. NPM versions file-based packages based on the filename changing. It won't check the package itself for an updated version in package.json, and the NPM team stated that they will not fix this, but people keep raising the issue: https://github.com/microsoft/WSL/issues/348

for now, just update the:

"version": "1.0.0-build5",

In the dependent package's package.json file, then update your reference to it in the main project to reference the new filename, ex:

"dependencies": {
       "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-1.0.0-build5.tgz",
        ...
}

You get used to it. Just update the two package.json files - version then the ref to the new filename.

Hope that helps someone...

Prevent Default on Form Submit jQuery

Try this:

$("#cpa-form").submit(function(e){
    return false;
});

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

PNG supports alphachannel transparency.

TIFF can have extended options I.e. Geo referencing for GIS applications.

I recommend only ever using JPEG for photographs, never for images like clip art, logos, text, diagrams, line art.

Favor PNG.

How to quickly drop a user with existing privileges

The accepted answer resulted in errors for me when attempting REASSIGN OWNED BY or DROP OWNED BY. The following worked for me:

REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;
DROP USER username;

The user may have privileges in other schemas, in which case you will have to run the appropriate REVOKE line with "public" replaced by the correct schema. To show all of the schemas and privilege types for a user, I edited the \dp command to make this query:

SELECT 
  n.nspname as "Schema",
  CASE c.relkind 
    WHEN 'r' THEN 'table' 
    WHEN 'v' THEN 'view' 
    WHEN 'm' THEN 'materialized view' 
    WHEN 'S' THEN 'sequence' 
    WHEN 'f' THEN 'foreign table' 
  END as "Type"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.array_to_string(c.relacl, E'\n') LIKE '%username%';

I'm not sure which privilege types correspond to revoking on TABLES, SEQUENCES, or FUNCTIONS, but I think all of them fall under one of the three.

How to call on a function found on another file?

Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.

Perhaps declare it above your first while?

SQL UPDATE with sub-query that references the same table in MySQL

Some reference for you http://dev.mysql.com/doc/refman/5.0/en/update.html

UPDATE user_account student 
INNER JOIN user_account teacher ON
   teacher.user_account_id = student.teacher_id 
   AND teacher.user_type = 'ROLE_TEACHER'
SET student.student_education_facility_id = teacher.education_facility_id

Difference between the Apache HTTP Server and Apache Tomcat?

In addition to the fine answers above, I think it should be said that Tomcat has it's own HTTP server built into it, and is fully functional at serving static content too. Depending on your java virtual machine configuration it can actually outperform going through traditional connectors in apache such as mod_proxy and mod_jk.

That said a fully optimized Tomcat server should serve static files fast and if you have Java servlets, JSPs and ColdFusion files in addition to static content you may find tomcat does an excellent job by itself.

How to remove all namespaces from XML with C#?

Here's are Regex Replace one liner:

public static string RemoveNamespaces(this string xml)
{
    return Regex.Replace(xml, "((?<=<|<\\/)|(?<= ))[A-Za-z0-9]+:| xmlns(:[A-Za-z0-9]+)?=\".*?\"", "");
}

Here's a sample: https://regex101.com/r/fopydN/6

Warning:there might be edge cases!

Can angularjs routes have optional parameter values?

Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl

You can use a function to generate the template string:

var app = angular.module('app',[]);

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id;   }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

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

New answer to new question:

You cannot return pointer to automatic variable (int c[5]) from the function. Automatic variable ends its lifetime with return enclosing block (function in this case) - so you are returning pointer to not existing array.

Either make your variable dynamic:

int* test (int a[5], int b[5]) {
    int* c = new int[5];
    for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
    return c;
}

Or change your implementation to use std::array:

std::array<int,5> test (const std::array<int,5>& a, const std::array<int,5>& b) 
{
   std::array<int,5> c;
   for (int i = 0; i < 5; i++) c[i] = a[i]+b[i];
   return c;
}

In case your compiler does not provide std::array you can replace it with simple struct containing an array:

struct array_int_5 { 
   int data[5];
   int& operator [](int i) { return data[i]; } 
   int operator const [](int i) { return data[i]; } 
};

Old answer to old question:

Your code is correct, and ... hmm, well, ... useless. Since arrays can be assigned to pointers without extra function (note that you are already using this in your function):

int arr[5] = {1, 2, 3, 4, 5};
//int* pArr = test(arr);
int* pArr = arr;

Morever signature of your function:

int* test (int in[5])

Is equivalent to:

int* test (int* in)

So you see it makes no sense.

However this signature takes an array, not pointer:

int* test (int (&in)[5])

Today's Date in Perl in MM/DD/YYYY format

You can do it fast, only using one POSIX function. If you have bunch of tasks with dates, see the module DateTime.

use POSIX qw(strftime);

my $date = strftime "%m/%d/%Y", localtime;
print $date;

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

if you experience this exception while using intellij and you are trying to start the application with the run button. Try starting the application from the command line instead. E.g. ensure that you are in the correct directory (directory with your pom file) assuming this is a springboot application run mvn spring-boot:run this did the trick for me.

Additionally I have also seen this error occur when your spring application depends on another application. In this case I had to start the other application first then run.

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

SELECT CONVERT(NVARCHAR(20), GETDATE(), 23)

Error:java: javacTask: source release 8 requires target release 1.8

If you are working with Android-studio 1.3, Follow the below steps -

Go to File - Project Structure

Under modules- app-Properties tab, choose Source Compatibility -1.8 and

Target Compatibility - 1.8.

And you are good to go.

Why do I get a SyntaxError for a Unicode escape in my file path?

I had the same error. Basically, I suspect that the path cannot start either with "U" or "User" after "C:\". I changed my directory to "c:\file_name.png" by putting the file that I want to access from python right under the 'c:\' path.

In your case, if you have to access the "python" folder, perhaps reinstall the python, and change the installation path to something like "c:\python". Otherwise, just avoid the "...\User..." in your path, and put your project under C:.

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

This is what worked for me (After trying every other solution i found ...):

Run adb reverse tcp:8081 tcp:8081 inside \Android\sdk\platform-tools

Convert varchar into datetime in SQL Server

SQL Server can implicitly cast strings in the form of 'YYYYMMDD' to a datetime - all other strings must be explicitly cast. here are two quick code blocks which will do the conversion from the form you are talking about:

version 1 uses unit variables:

BEGIN 
DECLARE @input VARCHAR(8), @mon CHAR(2), 
@day char(2), @year char(4), @output DATETIME

SET @input = '10022009'   --today's date


SELECT @mon = LEFT(@input, 2), @day = SUBSTRING(@input, 3,2), @year = RIGHT(@input,4)

SELECT @output = @year+@mon+@day 
SELECT @output 
END

version 2 does not use unit variables:

BEGIN 
DECLARE @input CHAR(8), @output DATETIME
SET @input = '10022009' --today's date 

SELECT @output = RIGHT(@input,4) + SUBSTRING(@input, 3,2) + LEFT(@input, 2)

SELECT @output
END

Both cases rely on sql server's ability to do that implicit conversion.

Regex for Mobile Number Validation

Satisfies all your requirements if you use the trick told below

Regex: /^(\+\d{1,3}[- ]?)?\d{10}$/

  1. ^ start of line
  2. A + followed by \d+ followed by a or - which are optional.
  3. Whole point two is optional.
  4. Negative lookahead to make sure 0s do not follow.
  5. Match \d+ 10 times.
  6. Line end.

DEMO Added multiline flag in demo to check for all cases

P.S. You really need to specify which language you use so as to use an if condition something like below:

// true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times

if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )

How to zip a file using cmd line?

You can use the following command:

zip -r nameoffile.zip directory

Hope this helps.

Extract csv file specific columns to list in Python

This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)

If you want your lists as in the question, you can now do:

names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()

How do I assign ls to an array in Linux Bash?

Whenever possible, you should avoid parsing the output of ls (see Greg's wiki on the subject). Basically, the output of ls will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */, what happens is that the shell expands */ to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls command isn't doing anything useful!

Well, ok, it is doing one thing that's useful: if there are no subdirectories, */ will get left as is, ls will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).

The cleaner way to make an array of subdirectory names is to use the glob (*/) without passing it to ls. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):

shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}"  # Note double-quotes to avoid extra parsing of funny characters in filenames

If you want to print an error message if there are no subdirectories, you're better off doing it yourself:

if (( ${#array[@]} == 0 )); then
    echo "No subdirectories found" >&2
fi

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

3 years already, but the same thing happened to me and I wanted to contribute with my case. Using the @nikk solution I got better results, but other errors still appeared, although yes, I was allowed to package.

However, my task was to implement the code of a co-worker on the server and it did not happen to him in his test environment, so I decided to investigate a little more since the code was functional and did not correspond to me touching anything .

In the end it turned out that his application inserted mysql tables into a database that did not exist. The solution was as easy as creating such a database and the error disappeared.

How to fix corrupted git repository?

I experienced similar issues using git version 2.7.1 under Ubuntu 18.04.3 lately. Here is how I did:

sudo apt install git-repair
git-repair  # fix a broken git repository
or
git-repair --force  # force repair, even if data is lost
git fsck  # to verify it was fixed

Most of the time the recovery process was successful

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

Using "margin: 0 auto;" in Internet Explorer 8

Form controls are replaced elements in CSS.

10.3.4 Block-level, replaced elements in normal flow

The used value of 'width' is determined as for inline replaced elements. Then the rules for non-replaced block-level elements are applied to determine the margins.

So the form control should not be stretched to 100% width.

However, it should be centered. It looks like an ordinary bug in IE8. It centers the element if you set specific width:

<input type="submit" style="display: block; width:100px; margin: 0 auto;" />

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

How to handle windows file upload using Selenium WebDriver?

The below one had worked for me

webDriver.findElement(By.xpath("//input[@type='file' and @name='importFile']")).sendKeys("C:/path/to/file.jpg");

How to use Redirect in the new react-router-dom of Reactjs

The simplest solution to navigate to another component is( Example navigates to mails component by click on icon):

<MailIcon 
  onClick={ () => { this.props.history.push('/mails') } }
/>

SQLite add Primary Key

According to the sqlite docs about table creation, using the create table as select produces a new table without constraints and without primary key.

However, the documentation also says that primary keys and unique indexes are logically equivalent (see constraints section):

In most cases, UNIQUE and PRIMARY KEY constraints are implemented by creating a unique index in the database. (The exceptions are INTEGER PRIMARY KEY and PRIMARY KEYs on WITHOUT ROWID tables.) Hence, the following schemas are logically equivalent:

CREATE TABLE t1(a, b UNIQUE);

CREATE TABLE t1(a, b PRIMARY KEY);

CREATE TABLE t1(a, b);
CREATE UNIQUE INDEX t1b ON t1(b); 

So, even if you cannot alter your table definition through SQL alter syntax, you can get the same primary key effect through the use an unique index.

Also, any table (except those created without the rowid syntax) have an inner integer column known as "rowid". According to the docs, you can use this inner column to retrieve/modify record tables.

Html table with button on each row

Pretty sure this solves what you're looking for:

HTML:

<table>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
</table>

Javascript (using jQuery):

$(document).ready(function(){
    $('.editbtn').click(function(){
        $(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
    });
});

Edit:

Apparently I should have looked at your sample code first ;)

You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.

By using classes, you can apply the same logic to multiple elements without any conflicts.

JSFiddle sample

Rename Files and Directories (Add Prefix)

This could be done running a simple find command:

find * -maxdepth 0 -exec mv {} PRE_{} \;

The above command will prefix all files and folders in the current directory with PRE_.

Do sessions really violate RESTfulness?

First of all, REST is not a religion and should not be approached as such. While there are advantages to RESTful services, you should only follow the tenets of REST as far as they make sense for your application.

That said, authentication and client side state do not violate REST principles. While REST requires that state transitions be stateless, this is referring to the server itself. At the heart, all of REST is about documents. The idea behind statelessness is that the SERVER is stateless, not the clients. Any client issuing an identical request (same headers, cookies, URI, etc) should be taken to the same place in the application. If the website stored the current location of the user and managed navigation by updating this server side navigation variable, then REST would be violated. Another client with identical request information would be taken to a different location depending on the server-side state.

Google's web services are a fantastic example of a RESTful system. They require an authentication header with the user's authentication key to be passed upon every request. This does violate REST principles slightly, because the server is tracking the state of the authentication key. The state of this key must be maintained and it has some sort of expiration date/time after which it no longer grants access. However, as I mentioned at the top of my post, sacrifices must be made to allow an application to actually work. That said, authentication tokens must be stored in a way that allows all possible clients to continue granting access during their valid times. If one server is managing the state of the authentication key to the point that another load balanced server cannot take over fulfilling requests based on that key, you have started to really violate the principles of REST. Google's services ensure that, at any time, you can take an authentication token you were using on your phone against load balance server A and hit load balance server B from your desktop and still have access to the system and be directed to the same resources if the requests were identical.

What it all boils down to is that you need to make sure your authentication tokens are validated against a backing store of some sort (database, cache, whatever) to ensure that you preserve as many of the REST properties as possible.

I hope all of that made sense. You should also check out the Constraints section of the wikipedia article on Representational State Transfer if you haven't already. It is particularly enlightening with regard to what the tenets of REST are actually arguing for and why.

Client to send SOAP request and receive response

I normally use another way to do the same

using System.Xml;
using System.Net;
using System.IO;

public static void CallWebService()
{
    var _url = "http://xxxxxxxxx/Service1.asmx";
    var _action = "http://xxxxxxxx/Service1.asmx?op=HelloWorld";

    XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
    HttpWebRequest webRequest = CreateWebRequest(_url, _action);
    InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);

    // begin async call to web request.
    IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

    // suspend this thread until call is complete. You might want to
    // do something usefull here like update your UI.
    asyncResult.AsyncWaitHandle.WaitOne();

    // get the response from the completed web request.
    string soapResult;
    using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
    {
        using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
        {
            soapResult = rd.ReadToEnd();
        }
        Console.Write(soapResult);        
    }
}

private static HttpWebRequest CreateWebRequest(string url, string action)
{
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Headers.Add("SOAPAction", action);
    webRequest.ContentType = "text/xml;charset=\"utf-8\"";
    webRequest.Accept = "text/xml";
    webRequest.Method = "POST";
    return webRequest;
}

private static XmlDocument CreateSoapEnvelope()
{
    XmlDocument soapEnvelopeDocument = new XmlDocument();
    soapEnvelopeDocument.LoadXml(
    @"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" 
               xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" 
               xmlns:xsd=""http://www.w3.org/1999/XMLSchema"">
        <SOAP-ENV:Body>
            <HelloWorld xmlns=""http://tempuri.org/"" 
                SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
                <int1 xsi:type=""xsd:integer"">12</int1>
                <int2 xsi:type=""xsd:integer"">32</int2>
            </HelloWorld>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>");
    return soapEnvelopeDocument;
}

private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
    using (Stream stream = webRequest.GetRequestStream())
    {
        soapEnvelopeXml.Save(stream);
    }
}

Wpf control size to content?

I had a problem like this whereby I had specified the width of my Window, but had the height set to Auto. The child DockPanel had it's VerticalAlignment set to Top and the Window had it's VerticalContentAlignment set to Top, yet the Window would still be much taller than the contents.

Using Snoop, I discovered that the ContentPresenter within the Window (part of the Window, not something I had put there) has it's VerticalAlignment set to Stretch and can't be changed without retemplating the entire Window!

After a lot of frustration, I discovered the SizeToContent property - you can use this to specify whether you want the Window to size vertically, horizontally or both, according to the size of the contents - everything is sizing nicely now, I just can't believe it took me so long to find that property!

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Another thing which worked was -

  1. Manually delete & then Create a designer file in filesystem.
  2. Edit Project file.
  3. Add code to include designer
    Eg: <Compile Include="<Path>\FileName.ascx.designer.cs"> <DependentUpon>FileName.ascx</DependentUpon> </Compile>
  4. Reload Project
  5. Open as(c/p)x file in design/view mode & save it.
  6. Check designer file. Code will be there.

Parsing JSON in Excel VBA

Two small contributions to Codo's answer:

' "recursive" version of GetObjectProperty
Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
    Dim names() As String
    Dim i As Integer

    names = Split(propertyName, ".")

    For i = 0 To UBound(names)
        Set JsonObject = ScriptEngine.Run("getProperty", JsonObject, names(i))
    Next

    Set GetObjectProperty = JsonObject
End Function

' shortcut to object array
Public Function GetObjectArrayProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object()
    Dim a() As Object
    Dim i As Integer
    Dim l As Integer

    Set JsonObject = GetObjectProperty(JsonObject, propertyName)

    l = GetProperty(JsonObject, "length") - 1

    ReDim a(l)

    For i = 0 To l
        Set a(i) = GetObjectProperty(JsonObject, CStr(i))
    Next

    GetObjectArrayProperty = a
End Function

So now I can do stuff like:

Dim JsonObject As Object
Dim Value() As Object
Dim i As Integer
Dim Total As Double

Set JsonObject = DecodeJsonString(CStr(request.responseText))

Value = GetObjectArrayProperty(JsonObject, "d.Data")

For i = 0 To UBound(Value)
    Total = Total + Value(i).Amount
Next

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

How do I get the offset().top value of an element without using jQuery?

You can try element[0].scrollTop, in my opinion this solution is faster.

Here you have bigger example - http://cvmlrobotics.blogspot.de/2013/03/angularjs-get-element-offset-position.html

PRINT statement in T-SQL

I recently ran into this, and it ended up being because I had a convert statement on a null variable. Since that was causing errors, the entire print statement was rendering as null, and not printing at all.

Example - This will fail:

declare @myID int=null
print 'First Statement: ' + convert(varchar(4), @myID)

Example - This will print:

declare @myID int=null
print 'Second Statement: ' +  coalesce(Convert(varchar(4), @myID),'@myID is null')

PHPExcel Make first row bold

Try this for range of cells:

$from = "A1"; // or any value
$to = "B5"; // or any value
$objPHPExcel->getActiveSheet()->getStyle("$from:$to")->getFont()->setBold( true );

or single cell

$cell_name = "A1";
$objPHPExcel->getActiveSheet()->getStyle( $cell_name )->getFont()->setBold( true );

hope that helps

SQLAlchemy equivalent to SQL "LIKE" statement

Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.

Note.query.filter(Note.message.match("%somestr%")).all()

It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.

For more info go Common Filter Operators

How to remove all whitespace from a string?

From stringr library you could try this:

  1. Remove consecutive fill blanks
  2. Remove fill blank

    library(stringr)

                2.         1.
                |          |
                V          V
    
        str_replace_all(str_trim(" xx yy 11 22  33 "), " ", "")
    

Running two projects at once in Visual Studio

Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.

This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).

Extract time from moment js object

You can do something like this

var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.

How to get number of video views with YouTube API?

You can use this too:

<?php
    $youtube_view_count = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json'))->entry->{'yt$statistics'}->viewCount;
    echo $youtube_view_count;
    ?>

How to compare dates in Java?

Following are most common way of comparing dates (my preference is Approach 1):

Approach 1: Using Date.before(), Date.after() and Date.equals()

if (date1.after(date2)) {
    System.out.println("Date1 is after Date2");
}

if (date1.before(date2)) {
    System.out.println("Date1 is before Date2");
}

if (date1.equals(date2)) {
    System.out.println("Date1 is equal Date2");
}

Approach 2: Date.compareTo()

if (date1.compareTo(date2) > 0) {
    System.out.println("Date1 is after Date2");
} else if (date1.compareTo(date2) < 0) {
    System.out.println("Date1 is before Date2");
} else {
    System.out.println("Date1 is equal to Date2");
}

Approach 3: Calender.before(), Calender.after() and Calender.equals()

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);

if (cal1.after(cal2)) {
    System.out.println("Date1 is after Date2");
}

if (cal1.before(cal2)) {
    System.out.println("Date1 is before Date2");
}

if (cal1.equals(cal2)) {
    System.out.println("Date1 is equal Date2");
}

add allow_url_fopen to my php.ini using .htaccess

If your host is using suPHP, you can try creating a php.ini file in the same folder as the script and adding:

allow_url_fopen = On

(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script

<?php
echo `id`;
?>

To give the same information, assuming shell_exec is not a disabled function)

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

A little late for the party, here's how I do it

  1. Undeploy application from manager
  2. Shutdown tomcat using ./shutdown.sh
  3. Delete browser cache
  4. Delete the application from webapps, and from /work/Catalina/...
  5. Startup tomcat using ./startup.sh
  6. Copy the new version of the application into /webapps and start it.

Python reading from a file and saving to utf-8

You can't do that using open. use codecs.

when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:

import codecs
file = codecs.open('data.txt','w','utf-8')

How can I force users to access my page over HTTPS instead of HTTP?

<?php 
// Require https
if ($_SERVER['HTTPS'] != "on") {
    $url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    header("Location: $url");
    exit;
}
?>

That easy.

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

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

Features:

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

Provided with plain LXC.

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

Provided with plain LXC.

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

Provided with plain LXC.

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

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

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

Docker provides this.

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

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

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

LXC already provides this.


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

Postgres could not connect to server

I got this same error. Turns out postgres just wasn't running at all (it is usually always running in the background, but for whatever reason it wasn't today).

If this is the case, just type postgres in the command line of your project directory

Binding Button click to a method

Some more explanations to the solution Rachel already gave:

"WPF Apps With The Model-View-ViewModel Design Pattern"

by Josh Smith

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Update select2 data without rebuilding the control

Diego's comment on the answer given by SpinyMan is important because the empty() method will remove the select2 instance, so any custom options will no longer be retained. If you want to keep existing select2 options you must save them, destroy the existing select2 instance, and then re-initialize. You can do that like so:

const options = JSON.parse(JSON.stringify(
  $('#inputhidden').data('select2').options.options
));
options.data = data;

$('#inputhidden').empty().select2('destroy').select2(options);

I would recommend to always explicitly pass the select2 options however, because the above only copies over simple options and not any custom callbacks or adapters. Also note that this requires the latest stable release of select2 (4.0.13 at the time of this post).

I wrote generic functions to handle this with a few features:

  • can handle selectors that return multiple instances
  • use the existing select2's instance options (default) or pass in a new set of options
  • keep any already-selected values (default) that are still valid, or clear them entirely
function select2UpdateOptions(
  selector,
  data,
  newOptions = null,
  keepExistingSelected = true
) {
  // loop through all instances of the matching selector and update each instance
  $(selector).each(function() {
    select2InstanceUpdateOptions($(this), data, newOptions, keepExistingSelected);
  });
}

// update an existing select2 instance with new data options
function select2InstanceUpdateOptions(
  instance,
  data,
  newOptions = null,
  keepSelected = true
) {
  // make sure this instance has select2 initialized
  // @link https://select2.org/programmatic-control/methods#checking-if-the-plugin-is-initialized
  if (!instance.hasClass('select2-hidden-accessible')) {
    return;
  }

  // get the currently selected options
  const existingSelected = instance.val();

  // by default use the existing options of the select2 instance unless overridden
  // this will not copy over any callbacks or custom adapters however
  const options = (newOptions)
    ? newOptions
    : JSON.parse(JSON.stringify(instance.data('select2').options.options))
  ;

  // set the new data options that will be used
  options.data = data;
      
  // empty the select and destroy the existing select2 instance
  // then re-initialize the select2 instance with the given options and data
  instance.empty().select2('destroy').select2(options);
      
  // by default keep options that were already selected;
  // any that are now invalid will automatically be cleared
  if (keepSelected) {
    instance.val(existingSelected).trigger('change');
  }
}

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

This problem started when I did 'Remove Unused References'. The website still worked on my local machine, but did not worked on the server after publishing.

Remove unused references

I fixed this problem by doing the following,

  1. Open 'Package Manager Console' in Visual Studio
  2. Uninstall-Package Microsoft.AspNet.Mvc
  3. Install-Package Microsoft.AspNet.Mvc

Amazon S3 - HTTPS/SSL - Is it possible?

payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:

https://s3-<region>.amazonaws.com/your.domain.com/some/asset

Where <region> is the bucket location name. For example, if your bucket is in the us-west-2 (Oregon) region, you can do this:

https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset

How to print a two dimensional array?

you can use the Utility mettod. Arrays.deeptoString();

 public static void main(String[] args) {
    int twoD[][] = new int[4][]; 
    twoD[0] = new int[1]; 
    twoD[1] = new int[2]; 
    twoD[2] = new int[3]; 
    twoD[3] = new int[4]; 

    System.out.println(Arrays.deepToString(twoD));

}

rename the columns name after cbind the data

A way of producing a data.frame and being able to do this in one line is to coerce all matrices/data frames passed to cbind into a data.frame while setting the column names attribute using setNames:

a = matrix(rnorm(10), ncol = 2)
b = matrix(runif(10), ncol = 2)

cbind(setNames(data.frame(a), c('n1', 'n2')), 
      setNames(data.frame(b), c('u1', 'u2')))

which produces:

          n1        n2         u1        u2
1 -0.2731750 0.5030773 0.01538194 0.3775269
2  0.5177542 0.6550924 0.04871646 0.4683186
3 -1.1419802 1.0896945 0.57212043 0.9317578
4  0.6965895 1.6973815 0.36124709 0.2882133
5  0.9062591 1.0625280 0.28034347 0.7517128

Unfortunately, there is no setColNames function analogous to setNames for data frames that returns the matrix after the column names, however, there is nothing to stop you from adapting the code of setNames to produce one:

setColNames <- function (object = nm, nm) {
    colnames(object) <- nm
    object
}

See this answer, the magrittr package contains functions for this.

Object of class stdClass could not be converted to string - laravel

Try this simple in one line of code:-

$data= json_decode( json_encode($data), true);

Hope it helps :)

How to get IntPtr from byte[] in C#

Another way,

GCHandle pinnedArray = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr pointer = pinnedArray.AddrOfPinnedObject();
// Do your stuff...
pinnedArray.Free();

Create Carriage Return in PHP String?

$postfields["message"] = "This is a sample ticket opened by the API\rwith a carriage return";

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

You can get this misleading error if you naively try to do this:

[clear] -> Private Key Encrypt -> [encrypted] -> Public Key Decrypt -> [clear]

Encrypting data using a private key is not allowed by design.

You can see from the command line options for open ssl that the only options to encrypt -> decrypt go in one direction public -> private.

  -encrypt        encrypt with public key
  -decrypt        decrypt with private key

The other direction is intentionally prevented because public keys basically "can be guessed." So, encrypting with a private key means the only thing you gain is verifying the author has access to the private key.

The private key encrypt -> public key decrypt direction is called "signing" to differentiate it from being a technique that can actually secure data.

  -sign           sign with private key
  -verify         verify with public key

Note: my description is a simplification for clarity. Read this answer for more information.

What is the "double tilde" (~~) operator in JavaScript?

~(5.5)   // => -6
~(-6)    // => 5
~~5.5    // => 5  (same as Math.floor(5.5))
~~(-5.5) // => -5 (NOT the same as Math.floor(-5.5), which would give -6 )

For more info, see:

Bash script to run php script

A previous poster said..

If you have PHP installed as a command line tool… your shebang (#!) line needs to look like this: #!/usr/bin/php

While this could be true… just because you can type in php does NOT necessarily mean that's where php is going to be... /usr/bin/php is A common location… but as with any shebang… it needs to be tailored to YOUR env.

a quick way to find out WHERE YOUR particular executable is located on your $PATH, try.. ?which -a php ENTER, which for me looks like..

php is /usr/local/php5/bin/php
php is /usr/bin/php
php is /usr/local/bin/php
php is /Library/WebServer/CGI-Executables/php

The first one is the default i'd get if I just typed in php at a command prompt… but I can use any of them in a shebang, or directly… You can also combine the executable name with env, as is often seen, but I don't really know much about / trust that. XOXO.

Cursor inside cursor

You could also sidestep nested cursor issues, general cursor issues, and global variable issues by avoiding the cursors entirely.

declare @rowid int
declare @rowid2 int
declare @id int
declare @type varchar(10)
declare @rows int
declare @rows2 int
declare @outer table (rowid int identity(1,1), id int, type varchar(100))
declare @inner table (rowid int  identity(1,1), clientid int, whatever int)

insert into @outer (id, type) 
Select id, type from sometable

select @rows = count(1) from @outer
while (@rows > 0)
Begin
    select top 1 @rowid = rowid, @id  = id, @type = type
    from @outer
    insert into @innner (clientid, whatever ) 
    select clientid whatever from contacts where contactid = @id
    select @rows2 = count(1) from @inner
    while (@rows2 > 0)
    Begin
        select top 1 /* stuff you want into some variables */
        /* Other statements you want to execute */
        delete from @inner where rowid = @rowid2
        select @rows2 = count(1) from @inner
    End  
    delete from @outer where rowid = @rowid
    select @rows = count(1) from @outer
End

Replace the single quote (') character from a string

Here are a few ways of removing a single ' from a string in python.

  • str.replace

    replace is usually used to return a string with all the instances of the substring replaced.

    "A single ' char".replace("'","")
    
  • str.translate

    In Python 2

    To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.

    "A single ' char".translate(None,"'")
    

    In Python 3

    You will have to use str.maketrans

    "A single ' char".translate(str.maketrans({"'":None}))
    
  • re.sub

    Regular Expressions using re are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.

    re.sub("'","","A single ' char")
    

Other Ways

There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string.

Another final method can be used also (Again not recommended - works only if there is only one occurrence )

  • Using list call along with remove and join.

    x = list(string)
    x.remove("'")
    ''.join(x)
    

height: 100% for <div> inside <div> with display: table-cell

This is exactly what you want:

HTML

<div class="table">

    <div class="cell">
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
    </div>
    <div class="cell">
        <div class="container">Text</div>
    </div>
</div>

CSS

.table {
    display: table;
    height:auto;
}

.cell {
    border: 2px solid black; 
    display:table-cell;
    vertical-align:top;
}

.container {
    height: 100%;
    overflow:auto;
    border: 2px solid green;
    -moz-box-sizing: border-box;
}

Add Insecure Registry to Docker

Create /etc/docker/daemon.json file where you want to pull docker images and add the following content to that file

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

Refer to my blog article for an in-depth explanation of creating a private docker registry: https://geekdosage.com/how-to-create-a-private-docker-registry-in-ubuntu-20-04/

Delete data with foreign key in SQL Server table

You can disable and re-enable the foreign key constraints before and after deleting:

alter table MyOtherTable nocheck constraint all
delete from MyTable
alter table MyOtherTable check constraint all

How to Alter a table for Identity Specification is identity SQL Server

You don't set value to default in a table. You should clear the option "Default value or Binding" first.

How to concat string + i?

according to this it looks like you have to set "N" before trying to use it and it looks like it needs to be an int not string? Don't know much bout MatLab but just what i gathered from that site..hope it helps :)

String contains another two strings

string d = "You hit someone for 50 damage";
string a = "damage";
string b = "someone";
string c = "you";

if(d.Contains(a) && d.Contains(b))
{
    Console.WriteLine(" " + d);
}
Console.ReadLine();