Programs & Examples On #Write through

Write-back vs Write-Through caching?

maybe this article can help you link here

Write-through: Write is done synchronously both to the cache and to the backing store.

Write-back (or Write-behind): Writing is done only to the cache. A modified cache block is written back to the store, just before it is replaced.

Write-through: When data is updated, it is written to both the cache and the back-end storage. This mode is easy for operation but is slow in data writing because data has to be written to both the cache and the storage.

Write-back: When data is updated, it is written only to the cache. The modified data is written to the back-end storage only when data is removed from the cache. This mode has fast data write speed but data will be lost if a power failure occurs before the updated data is written to the storage.

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

data=np.genfromtxt(csv_file, delimiter=',', dtype='unicode')

It works fine for me.

Adding Python Path on Windows 7

The following program will add the python executable path and the subdir Scripts (which is where e.g. pip and easy_install are installed) to your environment. It finds the path to the python executable from the registry key binding the .py extension. It will remove old python paths in your environment. Works with XP (and probably Vista) as well. It only uses modules that come with the basic windows installer.

# coding: utf-8

import sys
import os
import time
import _winreg
import ctypes

def find_python():
    """
    retrieves the commandline for .py extensions from the registry
    """
    hKey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,
                           r'Python.File\shell\open\command')
    # get the default value
    value, typ = _winreg.QueryValueEx (hKey, None)
    program = value.split('"')[1]
    if not program.lower().endswith(r'\python.exe'):
        return None
    return os.path.dirname(program)

def extend_path(pypath, remove=False, verbose=0, remove_old=True,
                script=False):
    """
    extend(pypath) adds pypath to the PATH env. variable as defined in the
    registry, and then notifies applications (e.g. the desktop) of this change.
    !!! Already opened DOS-Command prompts are not updated. !!!
    Newly opened prompts will have the new path (inherited from the 
    updated windows explorer desktop)
    options:
    remove (default unset), remove from PATH instead of extend PATH
    remove_old (default set), removes any (old) python paths first
    script (default unset), try to add/remove the Scripts subdirectory 
        of pypath (pip, easy_install) as well
    """
    _sd = 'Scripts' # scripts subdir
    hKey = _winreg.OpenKey (_winreg.HKEY_LOCAL_MACHINE,
               r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
               0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE)

    value, typ = _winreg.QueryValueEx (hKey, "PATH")
    vals = value.split(';')
    assert isinstance(vals, list)
    if not remove and remove_old:
        new_vals = []
        for v in vals:
            pyexe = os.path.join(v, 'python.exe')
            if v != pypath and os.path.exists(pyexe):
                if verbose > 0:
                    print 'removing from PATH:', v
                continue
            if script and v != os.path.join(pypath, _sd) and \
               os.path.exists(v.replace(_sd, pyexe)):
                if verbose > 0:
                    print 'removing from PATH:', v
                continue
            new_vals.append(v)
        vals = new_vals
    if remove:
        try:
            vals.remove(pypath)
        except ValueError:
            if verbose > 0:
                print 'path element', pypath, 'not found'
            return
        if script:
            try:
                vals.remove(os.path.join(pypath, _sd))
            except ValueError:
                pass
            print 'removing from PATH:', pypath
    else:
        if pypath in vals:
            if verbose > 0:
                print 'path element', pypath, 'already in PATH'
            return
        vals.append(pypath)
        if verbose > 1:
            print 'adding to PATH:', pypath
        if script:
            if not pypath + '\\Scripts' in vals:
                vals.append(pypath + '\\Scripts')
            if verbose > 1:
                print 'adding to PATH:', pypath + '\\Scripts'
    _winreg.SetValueEx(hKey, "PATH", 0, typ, ';'.join(vals) )
    _winreg.SetValueEx(hKey, "OLDPATH", 0, typ, value )
    _winreg.FlushKey(hKey)
    # notify other programs
    SendMessage = ctypes.windll.user32.SendMessageW
    HWND_BROADCAST = 0xFFFF
    WM_SETTINGCHANGE = 0x1A
    SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment')
    if verbose > 1:
        print 'Do not forget to restart any command prompts'

if __name__ == '__main__':
    remove = '--remove' in sys.argv
    script = '--noscripts' not in sys.argv
    extend_path(find_python(), verbose=2, remove=remove, script=script)

How to include NA in ifelse?

@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")

Or use isTRUE:

test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

Sure, have a look at IDA Pro. They offer an eval version so you can try it out.

ASP.Net which user account running Web Service on IIS 7?

Server 2008

Start Task Manager Find w3wp.exe process (description IIS Worker Process) Check User Name column to find who you're IIS process is running as.

In the IIS GUI you can configure your application pool to run as a specific user: Application Pool default Advanced Settings Identity

Here's the info from Microsoft on setting up Application Pool Identites:

http://learn.iis.net/page.aspx/624/application-pool-identities/

Execute combine multiple Linux commands in one line

I've found that using ; to separate commands only works in the foreground. eg :

cmd1; cmd2; cmd3 & - will only execute cmd3 in the background, whereas cmd1 && cmd2 && cmd3 & - will execute the entire chain in the background IF there are no errors.

To cater for unconditional execution, using parenthesis solves this :

(cmd1; cmd2; cmd3) & - will execute the chain of commands in the background, even if any step fails.

How to programmatically set cell value in DataGridView?

I tried a lot of methods, and the only one which worked was UpdateCellValue:

dataGridView.Rows[rowIndex].Cells[columnIndex].Value = "New Value";
dataGridView.UpdateCellValue(columnIndex, rowIndex);

I hope to have helped. =)

SecurityError: The operation is insecure - window.history.pushState()

I solved it by switching tohttp protocol from the file protocol.

  • you can use "live-server" extension in VS code,
  • or, on node, use live-server [dirPath]

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

sorting a vector of structs

Use a comparison function:

bool compareByLength(const data &a, const data &b)
{
    return a.word.size() < b.word.size();
}

and then use std::sort in the header #include <algorithm>:

std::sort(info.begin(), info.end(), compareByLength);

How to use a RELATIVE path with AuthUserFile in htaccess?

.htpasswd requires full absolute path from the absolute root of the server.

Please get full absolute path of the file by echo echo $_SERVER['DOCUMENT_ROOT'];.

here is working basic auth .htaccess script.

AuthType Basic
AuthName "Access to the Hidden Files"
AuthUserFile 'C:/xampp/htdocs/ht/.htpasswd'
Require valid-user

Before login

enter image description here

Afetr Login

enter image description here

System.drawing namespace not found under console application

For,Adding System.Drawing Follow some steps: Firstly, right click on the solution and click on add Reference. Secondly, Select the .NET Folder. And then double click on the Using.System.Drawing;

Regex to validate password strength

All of above regex unfortunately didn't worked for me. A strong password's basic rules are

  • Should contain at least a capital letter
  • Should contain at least a small letter
  • Should contain at least a number
  • Should contain at least a special character
  • And minimum length

So, Best Regex would be

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*]).{8,}$

The above regex have minimum length of 8. You can change it from {8,} to {any_number,}

Modification in rules?

let' say you want minimum x characters small letters, y characters capital letters, z characters numbers, Total minimum length w. Then try below regex

^(?=.*[a-z]{x,})(?=.*[A-Z]{y,})(?=.*[0-9]{z,})(?=.*[!@#\$%\^&\*]).{w,}$

Note: Change x, y, z, w in regex

Edit: Updated regex answer

Edit2: Added modification

How can I make git accept a self signed certificate?

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

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

How to print register values in GDB?

If you're trying to print a specific register in GDB, you have to omit the % sign. For example,

info registers eip

If your executable is 64 bit, the registers start with r. Starting them with e is not valid.

info registers rip

Those can be abbreviated to:

i r rip

Which is faster: multiple single INSERTs or one multiple-row INSERT?

https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html

The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:

  • Connecting: (3)
  • Sending query to server: (2)
  • Parsing query: (2)
  • Inserting row: (1 × size of row)
  • Inserting indexes: (1 × number of indexes)
  • Closing: (1)

From this it should be obvious, that sending one large statement will save you an overhead of 7 per insert statement, which in further reading the text also says:

If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements.

How to make div follow scrolling smoothly with jQuery?

I wrote a relatively simple answer for this.

I have a table that's using one of the "sticky table header" plugins to stick right below a particular div on my page, but the menu to the left of the table didn't stick (as it's not part of the table.)

For my purposes, I knew the div that needed "stickiness" was always going to start at 385 pixels below the top of the window, so I created an empty div right above that:

<div id="stopMenu" class="stopMenu"></div>

Then ran this:

$(window).scroll(function(){   
   if ( $(window).scrollTop() > 385 ) {
    extraPadding = $(window).scrollTop() - 385;
    $('#stopMenu').css( "padding-top", extraPadding );
   } else {
     $('#stopMenu').css( "padding-top", "0" );
   }
});

As the user scrolls, it adds whatever the value of $(window).scrollTop() is to the integer 385, then adds that value to the stopMenu div that's above the thing I want to stay focused.

In the event the user scrolls all the way back up, I just set the extra padding to 0.

This doesn't require the user to do anything IN CSS particularly, but it's kind of a nice effect to make a small delay, so I put the class="stopMenu" in as well:

.stopMenu {
  .transition: all 0.1s;
}

jQuery Screen Resolution Height Adjustment

var space = $(window).height();
var diff = space - HEIGHT;
var margin = (diff > 0) ? (space - HEIGHT)/2 : 0;
$('#container').css({'margin-top': margin});

Java: Integer equals vs. ==

You can't compare two Integer with a simple == they're objects so most of the time references won't be the same.

There is a trick, with Integer between -128 and 127, references will be the same as autoboxing uses Integer.valueOf() which caches small integers.

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.


Resources :

On the same topic :

How do I check if an element is hidden in jQuery?

You can use the

$( "div:visible" ).click(function() {
  $( this ).css( "background", "yellow" );
});
$( "button" ).click(function() {
  $( "div:hidden" ).show( "fast" );
});

API Documentation: visible Selector

Run bash script as daemon

A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...

[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]

The simple way:

The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):

sudo nano /etc/rc.local

Add the following and save:

#For a BASH script
/bin/sh TheNameOfYourScript.sh > /dev/null &

The better way to do this would be to create a Daemon via Upstart:

sudo nano /etc/init/TheNameOfYourDaemon.conf

add the following:

description "My Daemon Job"
author "Your Name"
start on runlevel [2345]    

pre-start script
  echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log
end script

exec /bin/sh TheNameOfYourScript.sh > /dev/null &

Save this.

Confirm that it looks ok:

init-checkconf /etc/init/TheNameOfYourDaemon.conf

Now reboot the machine:

sudo reboot

Now when you boot up your system, you can see the log file stating that your Daemon is running:

cat  /var/log/TheNameOfYourDaemonJobLog.log

• Now you may start/stop/restart/get the status of your Daemon via:

restart: this will stop, then start a service

sudo service TheNameOfYourDaemonrestart restart

start: this will start a service, if it's not running

sudo service TheNameOfYourDaemonstart start

stop: this will stop a service, if it's running

sudo service TheNameOfYourDaemonstop stop

status: this will display the status of a service

sudo service TheNameOfYourDaemonstatus status

Insert Picture into SQL Server 2005 Image Field using only SQL

CREATE TABLE Employees
(
    Id int,
    Name varchar(50) not null,
    Photo varbinary(max) not null
)


INSERT INTO Employees (Id, Name, Photo) 
SELECT 10, 'John', BulkColumn 
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture

Text-decoration: none not working

Try placing your text-decoration: none; on your a:hover css.

Properties file with a list as the value for an individual key

Your logic is flawed... basically, you need to:

  1. get the list for the key
  2. if the list is null, create a new list and put it in the map
  3. add the word to the list

You're not doing step 2.

Here's the code you want:

Properties prop = new Properties();
prop.load(new FileInputStream("/displayCategerization.properties"));
for (Map.Entry<Object, Object> entry : prop.entrySet())
{
    List<String> categoryList = categoryMap.get((String) entry.getKey());
    if (categoryList == null)
    {
        categoryList = new ArrayList<String>();
        LogDisplayService.categoryMap.put((String) entry.getKey(), categoryList);
    }
    categoryList.add((String) entry.getValue());
}

Note also the "correct" way to iterate over the entries of a map/properties - via its entrySet().

Inline IF Statement in C#

You can do inline ifs with

return y == 20 ? 1 : 2;

which will give you 1 if true and 2 if false.

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

What's the difference between the Window.Loaded and Window.ContentRendered events

If you're using data binding, then you need to use the ContentRendered event.

For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.

<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />

val() vs. text() for textarea

.val() always works with textarea elements.

.text() works sometimes and fails other times! It's not reliable (tested in Chrome 33)

What's best is that .val() works seamlessly with other form elements too (like input) whereas .text() fails.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

I had a similar issue which i solved by making two changes

  1. added below entry in application.yaml file

    spring: jackson: serialization.write_dates_as_timestamps: false

  2. add below two annotations in pojo

    1. @JsonDeserialize(using = LocalDateDeserializer.class)
    2. @JsonSerialize(using = LocalDateSerializer.class)

    sample example

    import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; public class Customer { //your fields ... @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) protected LocalDate birthdate; }

then the following json requests worked for me

  1. sample request format as string

{ "birthdate": "2019-11-28" }

  1. sample request format as array

{ "birthdate":[2019,11,18] }

Hope it helps!!

How can I create a UIColor from a hex string?

Use Xcode's native Color Literals feature to add hex colors easily and natively.

Type Color Literal into your code and let Xcode autocomplete do the rest.

The color picker UI will allow you to paste in a Hex Color: #FF9300

color picker

The git diff of the macro will show RGB values rather than hex:

let orange = #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)

But it's still an easy way to paste in hex without any 3rd party tools or extensions.

How to use lodash to find and return an object from Array?

Import lodash using

$ npm i --save lodash

var _ = require('lodash'); 

var objArrayList = 
    [
         { name: "user1"},
         { name: "user2"}, 
         { name: "user2"}
    ];

var Obj = _.find(objArrayList, { name: "user2" });

// Obj ==> { name: "user2"}

How to build & install GLFW 3 and use it in a Linux project

If anyone's getting lazy and maybe perhaps doesn't know how to configure shell for all those libraries and -ls, then I created a python script(you have to have python3, most linux users have it.) that allows you to easily compile scripts and run them without worrying much, it just has regular system calls, just arranged neatly, I created it for my self but maybe it'd be useful: Here it is

T-SQL: Selecting rows to delete via joins

In SQLite, the only thing that work is something similar to beauXjames' answer.

It seems to come down to this DELETE FROM table1 WHERE table1.col1 IN (SOME TEMPORARY TABLE); and that some temporary table can be crated by SELECT and JOIN your two table which you can filter this temporary table based on the condition that you want to delete the records in Table1.

How do you format code on save in VS Code

As of September 2016 (VSCode 1.6), this is now officially supported.

Add the following to your settings.json file:

"editor.formatOnSave": true

Create Excel files from C# without office

Try EPPlus if you use Excel 2007. Supports ranges, cellstyling, charts, shapes, pictures and a lot of other stuff

Running an Excel macro via Python?

A variation on SMNALLY's code that doesn't quit Excel if you already have it open:

import os, os.path
import win32com.client
    
if os.path.exists("excelsheet.xlsm"):
    xl=win32com.client.Dispatch("Excel.Application")
    wb = xl.Workbooks.Open(os.path.abspath("excelsheet.xlsm"), ReadOnly=1) #create a workbook object
    xl.Application.Run("excelsheet.xlsm!modulename.macroname")
    wb.Close(False) #close the work sheet object rather than quitting excel
    del wb
    del xl

Best Practice for Forcing Garbage Collection in C#

One case I recently encountered that required manual calls to GC.Collect() was when working with large C++ objects that were wrapped in tiny managed C++ objects, which in turn were accessed from C#.

The garbage collector never got called because the amount of managed memory used was negligible, but the amount of unmanaged memory used was huge. Manually calling Dispose() on the objects would require that I keep track of when objects are no longer needed myself, whereas calling GC.Collect() will clean up any objects that are no longer referred.....

Determine version of Entity Framework I am using?

There are two versions: 1 and 4. EFv4 is part of .net 4.0, and EFv1 is part of .net 3.5 SP1.

Yes, the config setting above points to EFv4 / .net 4.0.

EDIT If you open the references folder and locate system.data.entity, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows runtime version v4.0.30319 with the Version property showing 4.0.0.0. The EntityFramework.dll can be viewed in this fashion also. Only the Version will be 4.1.0.0 and the Runtime version will be v4.0.30319 which specifies it is a .NET 4 component. Alternatively, you can open the file location as listed in the Path property and right-click the component in question, choose properties, then choose the details tab and view the product version.

Simple int to char[] conversion

Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

char c[2];
int i=1;
sprintf(c, "%d", i);

Output ("echo") a variable to a text file

Your sample code seems to be OK. Thus, the root problem needs to be dug up somehow. Let's eliminate chance for typos in the script. First off, make sure you put Set-Strictmode -Version 2.0 in the beginning of your script. This will help you to catch misspelled variable names. Like so,

# Test.ps1
set-strictmode -version 2.0 # Comment this line and no error will be reported.
$foo = "bar"
set-content -path ./test.txt -value $fo # Error! Should be "$foo"

PS C:\temp> .\test.ps1
The variable '$fo' cannot be retrieved because it has not been set.
At C:\temp\test.ps1:3 char:40
+ set-content -path ./test.txt -value $fo <<<<
    + CategoryInfo          : InvalidOperation: (fo:Token) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

The next part about question marks sounds like you have a problem with Unicode. What's the output when you type the file with Powershell like so,

$file = "\\server\share\file.txt"
cat $file

td widths, not working?

You can't specify units in width/height attributes of a table; these are always in pixels, but you should not use them at all since they are deprecated.

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

if you add your remote repository by using git clone then follow the steps:-

git clone <repo_url> then

git init

git add * *means add all files

git commit -m 'your commit'

git remote -v for check any branch run or not if not then nothing show then we add or fetch the repository. "fetch first". You need to run git pull origin <branch> or git pull -r origin <branch> before a next push.

then

git remote add origin <git url>
 git pull -r origin master
git push -u origin master```

Using Bootstrap Modal window as PartialView

I do this with mustache.js and templates (you could use any JavaScript templating library).

In my view, I have something like this:

<script type="text/x-mustache-template" id="modalTemplate">
    <%Html.RenderPartial("Modal");%>
</script>

...which lets me keep my templates in a partial view called Modal.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
    <div>
        <div class="modal-header">
            <a class="close" data-dismiss="modal">&times;</a>
            <h3>{{Name}}</h3>
        </div>
        <div class="modal-body">
            <table class="table table-striped table-condensed">
                <tbody>
                    <tr><td>ID</td><td>{{Id}}</td></tr>
                    <tr><td>Name</td><td>{{Name}}</td></tr>
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <a class="btn" data-dismiss="modal">Close</a>
        </div>
    </div>

I create placeholders for each modal in my view:

<%foreach (var item in Model) {%>
    <div data-id="<%=Html.Encode(item.Id)%>"
         id="modelModal<%=Html.Encode(item.Id)%>" 
         class="modal hide fade">
    </div>
<%}%>

...and make ajax calls with jQuery:

<script type="text/javascript">
    var modalTemplate = $("#modalTemplate").html()
    $(".modal[data-id]").each(function() {
        var $this = $(this)
        var id = $this.attr("data-id")
        $this.on("show", function() {
            if ($this.html()) return
            $.ajax({
                type: "POST",
                url: "<%=Url.Action("SomeAction")%>",
                data: { id: id },
                success: function(data) {
                    $this.append(Mustache.to_html(modalTemplate, data))
                }
            })
        })
    })
</script>

Then, you just need a trigger somewhere:

<%foreach (var item in Model) {%>
    <a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
        <%=Html.Encode(item.DutModel.Name)%>
    </a>
<%}%>

Difference between two DateTimes C#?

You can do the following:

TimeSpan duration = b - a;

There's plenty of built in methods in the timespan class to do what you need, i.e.

duration.TotalSeconds
duration.TotalMinutes

More info can be found here.

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

This was resolved. It turns out our IT Staff was correct. Both TLS 1.1 and TLS 1.2 were installed on the server. However, the issue was that our sites are running as ASP.NET 4.0 and you have to have ASP.NET 4.5 to run TLS 1.1 or TLS 1.2. So, to resolve the issue, our IT Staff had to re-enable TLS 1.0 to allow a connection with PayTrace.

So in short, the error message, "the client and server cannot communicate, because they do not possess a common algorithm", was caused because there was no SSL Protocol available on the server to communicate with PayTrace's servers.

UPDATE: Please do not enable TLS 1.0 on your servers, this was a temporary fix and is not longer applicable since there are now better work-arounds that ensure strong security practices. Please see accepted answer for a solution. FYI, I'm going to keep this answer on the site as it provides information on what the problem was, please do not down-vote.

ValueError: setting an array element with a sequence

From the code you showed us, the only thing we can tell is that you are trying to create an array from a list that isn't shaped like a multi-dimensional array. For example

numpy.array([[1,2], [2, 3, 4]])

or

numpy.array([[1,2], [2, [3, 4]]])

will yield this error message, because the shape of the input list isn't a (generalised) "box" that can be turned into a multidimensional array. So probably UnFilteredDuringExSummaryOfMeansArray contains sequences of different lengths.

Edit: Another possible cause for this error message is trying to use a string as an element in an array of type float:

numpy.array([1.2, "abc"], dtype=float)

That is what you are trying according to your edit. If you really want to have a NumPy array containing both strings and floats, you could use the dtype object, which enables the array to hold arbitrary Python objects:

numpy.array([1.2, "abc"], dtype=object)

Without knowing what your code shall accomplish, I can't judge if this is what you want.

How to compare two Carbon Timestamps?

Carbon has a bunch of comparison functions with mnemonic names:

  • equalTo()
  • notEqualTo()
  • greaterThan()
  • greaterThanOrEqualTo()
  • lessThan()
  • lessThanOrEqualTo()

Usage:

 if($model->edited_at->greaterThan($model->created_at)){
     // edited at is newer than created at
 }

Valid for nesbot/carbon 1.36.2

if you are not sure what Carbon version you are on, run this

$composer show "nesbot/carbon"

documentation: https://carbon.nesbot.com/docs/#api-comparison

Query to list all users of a certain group

For Active Directory users, an alternative way to do this would be -- assuming all your groups are stored in OU=Groups,DC=CorpDir,DC=QA,DC=CorpName -- to use the query (&(objectCategory=group)(CN=GroupCN)). This will work well for all groups with less than 1500 members. If you want to list all members of a large AD group, the same query will work, but you'll have to use ranged retrieval to fetch all the members, 1500 records at a time.

The key to performing ranged retrievals is to specify the range in the attributes using this syntax: attribute;range=low-high. So to fetch all members of an AD Group with 3000 members, first run the above query asking for the member;range=0-1499 attribute to be returned, then for the member;range=1500-2999 attribute.

Vue.js - How to properly watch for nested data

Tracking individual changed items in a list

If you want to watch all items in a list and know which item in the list changed, you can set up custom watchers on every item separately, like so:

var vm = new Vue({
  data: {
    list: [
      {name: 'obj1 to watch'},
      {name: 'obj2 to watch'},
    ],
  },
  methods: {
    handleChange (newVal, oldVal) {
      // Handle changes here!
      // NOTE: For mutated objects, newVal and oldVal will be identical.
      console.log(newVal);
    },
  },
  created () {
    this.list.forEach((val) => {
      this.$watch(() => val, this.handleChange, {deep: true});
    });
  },
});

If your list isn't populated straight away (like in the original question), you can move the logic out of created to wherever needed, e.g. inside the .then() block.

Watching a changing list

If your list itself updates to have new or removed items, I've developed a useful pattern that "shallow" watches the list itself, and dynamically watches/unwatches items as the list changes:

// NOTE: This example uses Lodash (_.differenceBy and _.pull) to compare lists
//       and remove list items. The same result could be achieved with lots of
//       list.indexOf(...) if you need to avoid external libraries.

var vm = new Vue({
  data: {
    list: [
      {name: 'obj1 to watch'},
      {name: 'obj2 to watch'},
    ],
    watchTracker: [],
  },
  methods: {
    handleChange (newVal, oldVal) {
      // Handle changes here!
      console.log(newVal);
    },
    updateWatchers () {
      // Helper function for comparing list items to the "watchTracker".
      const getItem = (val) => val.item || val;

      // Items that aren't already watched: watch and add to watched list.
      _.differenceBy(this.list, this.watchTracker, getItem).forEach((item) => {
        const unwatch = this.$watch(() => item, this.handleChange, {deep: true});
        this.watchTracker.push({ item: item, unwatch: unwatch });
        // Uncomment below if adding a new item to the list should count as a "change".
        // this.handleChange(item);
      });

      // Items that no longer exist: unwatch and remove from the watched list.
      _.differenceBy(this.watchTracker, this.list, getItem).forEach((watchObj) => {
        watchObj.unwatch();
        _.pull(this.watchTracker, watchObj);
        // Optionally add any further cleanup in here for when items are removed.
      });
    },
  },
  watch: {
    list () {
      return this.updateWatchers();
    },
  },
  created () {
    return this.updateWatchers();
  },
});

Best way to access a control on another form in Windows Forms?

  1. Use an event handler to notify other the form to handle it.
  2. Create a public property on the child form and access it from parent form (with a valid cast).
  3. Create another constructor on the child form for setting form's initialization parameters
  4. Create custom events and/or use (static) classes.

The best practice would be #4 if you are using non-modal forms.

git status (nothing to commit, working directory clean), however with changes commited

git status output tells you three things by default:

  1. which branch you are on
  2. What is the status of your local branch in relation to the remote branch
  3. If you have any uncommitted files

When you did git commit , it committed to your local repository, thus #3 shows nothing to commit, however, #2 should show that you need to push or pull if you have setup the tracking branch.

If you find the output of git status verbose and difficult to comprehend, try using git status -sb this is less verbose and will show you clearly if you need to push or pull. In your case, the output would be something like:

master...origin/master [ahead 1]

git status is pretty useful, in the workflow you described do a git status -sb: after touching the file, after adding the file and after committing the file, see the difference in the output, it will give you more clarity on untracked, tracked and committed files.

Update #1
This answer is applicable if there was a misunderstanding in reading the git status output. However, as it was pointed out, in the OPs case, the upstream was not set correctly. For that, Chris Mae's answer is correct.

How to split csv whose columns may contain ,

It is so much late but this can be helpful for someone. We can use RegEx as bellow.

Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
String[] Fields = CSVParser.Split(Test);

Column name or number of supplied values does not match table definition

The problem I had that caused this error was that I was trying to insert null values into a NOT NULL column.

Is it necessary to assign a string to a variable before comparing it to another?

Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:

NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];

Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.

Next time you want a string variable you can use the "@" symbol in a much more convenient way:

NSString *myString = @"SomeText";

This will be autoreleased when you've finished with it so you'll avoid memory leaks too...

Hope that helps!

How do you create a Marker with a custom icon for google maps API v3?

Symbol You Want on Color You Want!

I was looking for this answer for days and here it is the right and easy way to create a custom marker:

'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=xxx%7c5680FC%7c000000&.png' where xxx is the text and 5680fc is the hexadecimal color code of the background and 000000 is the hexadecimal color code of the text.

Theses markers are totally dynamic and you can create whatever balloon icon you want. Just change the URL.

How to check radio button is checked using JQuery?

Radio buttons are,

<input type="radio" id="radio_1" class="radioButtons" name="radioButton" value="1">
<input type="radio" id="radio_2" class="radioButtons" name="radioButton" value="2">

to check on click,

$('.radioButtons').click(function(){
    if($("#radio_1")[0].checked){
       //logic here
    }
});

Simulate string split function in Excel formula

If you need the allocation to the columns only once the answer is the "Text to Columns" functionality in MS Excel.

See MS help article here: http://support.microsoft.com/kb/214261

HTH

How to define relative paths in Visual Studio Project?

If I get you right, you need ..\..\src

How to print a list with integers without the brackets, commas and no quotes?

You can convert it to a string, and then to an int:

print(int("".join(str(x) for x in [7,7,7,7])))

How to convert int to Integer

i it integer, int to Integer

Integer intObj = new Integer(i);

add to collection

list.add(String.valueOf(intObj));

Check if all checkboxes are selected

$('.abc[checked!=true]').length == 0

ng-change not working on a text input

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

Python Socket Multiple Clients

This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.

#!usr/bin/python
from thread import *
import socket
import sys

def clientthread(conn):
    buffer=""
    while True:
        data = conn.recv(8192)
        buffer+=data
        print buffer
    #conn.sendall(reply)
    conn.close()

def main():
    try:
        host = '192.168.1.3'
        port = 6666
        tot_socket = 26
        list_sock = []
        for i in range(tot_socket):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            s.bind((host, port+i))
            s.listen(10)
            list_sock.append(s)
            print "[*] Server listening on %s %d" %(host, (port+i))

        while 1:
            for j in range(len(list_sock)):
                conn, addr = list_sock[j].accept()
                print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
                start_new_thread(clientthread ,(conn,))
        s.close()

    except KeyboardInterrupt as msg:
        sys.exit(0)


if __name__ == "__main__":
    main()

Default value in an asp.net mvc view model

Use specific value:

[Display(Name = "Date")]
public DateTime EntryDate {get; set;} = DateTime.Now;//by C# v6

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

Set margins in a LinearLayout programmatically

So that works fine, but how on earth do you give the buttons margins so there is space between them?

You call setMargins() on the LinearLayout.LayoutParams object.

I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good.

LinearLayout.LayoutParams is a subclass of LinearLayout.MarginLayoutParams, as indicated in the documentation.

Is this impossible?

No.

it wouldn't be the first Android layout task you can only do in XML

You are welcome to supply proof of this claim.

Personally, I am unaware of anything that can only be accomplished via XML and not through Java methods in the SDK. In fact, by definition, everything has to be doable via Java (though not necessarily via SDK-reachable methods), since XML is not executable code. But, if you're aware of something, point it out, because that's a bug in the SDK that should get fixed someday.

Getting value of HTML Checkbox from onclick/onchange events

The short answer:

Use the click event, which won't fire until after the value has been updated, and fires when you want it to:

<label><input type='checkbox' onclick='handleClick(this);'>Checkbox</label>

function handleClick(cb) {
  display("Clicked, new value = " + cb.checked);
}

Live example | Source

The longer answer:

The change event handler isn't called until the checked state has been updated (live example | source), but because (as Tim Büthe points out in the comments) IE doesn't fire the change event until the checkbox loses focus, you don't get the notification proactively. Worse, with IE if you click a label for the checkbox (rather than the checkbox itself) to update it, you can get the impression that you're getting the old value (try it with IE here by clicking the label: live example | source). This is because if the checkbox has focus, clicking the label takes the focus away from it, firing the change event with the old value, and then the click happens setting the new value and setting focus back on the checkbox. Very confusing.

But you can avoid all of that unpleasantness if you use click instead.

I've used DOM0 handlers (onxyz attributes) because that's what you asked about, but for the record, I would generally recommend hooking up handlers in code (DOM2's addEventListener, or attachEvent in older versions of IE) rather than using onxyz attributes. That lets you attach multiple handlers to the same element and lets you avoid making all of your handlers global functions.


An earlier version of this answer used this code for handleClick:

function handleClick(cb) {
  setTimeout(function() {
    display("Clicked, new value = " + cb.checked);
  }, 0);
}

The goal seemed to be to allow the click to complete before looking at the value. As far as I'm aware, there's no reason to do that, and I have no idea why I did. The value is changed before the click handler is called. In fact, the spec is quite clear about that. The version without setTimeout works perfectly well in every browser I've tried (even IE6). I can only assume I was thinking about some other platform where the change isn't done until after the event. In any case, no reason to do that with HTML checkboxes.

How to update a claim in ASP.NET Identity?

Multiple Cookies,Multiple Claims

public class ClaimsCookie
    {
        private readonly ClaimsPrincipal _user;
        private readonly HttpContext _httpContext;
        public ClaimsCookie(ClaimsPrincipal user, HttpContext httpContext = null)
        {
            _user = user;
            _httpContext = httpContext;
        }

        public string GetValue(CookieName cookieName, KeyName keyName)
        {
            var principal = _user as ClaimsPrincipal;
            var cp = principal.Identities.First(i => i.AuthenticationType == ((CookieName)cookieName).ToString());
            return cp.FindFirst(((KeyName)keyName).ToString()).Value;
        }
        public async void SetValue(CookieName cookieName, KeyName[] keyName, string[] value)
        {
            if (keyName.Length != value.Length)
            {
                return;
            }
            var principal = _user as ClaimsPrincipal;
            var cp = principal.Identities.First(i => i.AuthenticationType == ((CookieName)cookieName).ToString());
            for (int i = 0; i < keyName.Length; i++)
            {
                if (cp.FindFirst(((KeyName)keyName[i]).ToString()) != null)
                {
                    cp.RemoveClaim(cp.FindFirst(((KeyName)keyName[i]).ToString()));
                    cp.AddClaim(new Claim(((KeyName)keyName[i]).ToString(), value[i]));
                }

            }
            await _httpContext.SignOutAsync(CookieName.UserProfilCookie.ToString());
            await _httpContext.SignInAsync(CookieName.UserProfilCookie.ToString(), new ClaimsPrincipal(cp),
                new AuthenticationProperties
                {
                    IsPersistent = bool.Parse(cp.FindFirst(KeyName.IsPersistent.ToString()).Value),
                    AllowRefresh = true
                });
        }
        public enum CookieName
        {
            CompanyUserProfilCookie = 0, UserProfilCookie = 1, AdminPanelCookie = 2
        }
        public enum KeyName
        {
            Id, Name, Surname, Image, IsPersistent
        }
    }

Instantly detect client disconnection from server socket

Expanding on comments by mbargiel and mycelo on the accepted answer, the following can be used with a non-blocking socket on the server end to inform whether the client has shut down.

This approach does not suffer the race condition that affects the Poll method in the accepted answer.

// Determines whether the remote end has called Shutdown
public bool HasRemoteEndShutDown
{
    get
    {
        try
        {
            int bytesRead = socket.Receive(new byte[1], SocketFlags.Peek);

            if (bytesRead == 0)
                return true;
        }
        catch
        {
            // For a non-blocking socket, a SocketException with 
            // code 10035 (WSAEWOULDBLOCK) indicates no data available.
        }

        return false;
    }
}

The approach is based on the fact that the Socket.Receive method returns zero immediately after the remote end shuts down its socket and we've read all of the data from it. From Socket.Receive documentation:

If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.

If you are in non-blocking mode, and there is no data available in the protocol stack buffer, the Receive method will complete immediately and throw a SocketException.

The second point explains the need for the try-catch.

Use of the SocketFlags.Peek flag leaves any received data untouched for a separate receive mechanism to read.

The above will work with a blocking socket as well, but be aware that the code will block on the Receive call (until data is received or the receive timeout elapses, again resulting in a SocketException).

How to detect if URL has changed after hash in JavaScript

window.addEventListener("beforeunload", function (e) {
    // do something
}, false);

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

Although there's CSS defines a text-wrap property, it's not supported by any major browser, but maybe vastly supported white-space property solves your problem.

How to write data to a JSON file using Javascript

JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage

    var obj = {"nissan": "sentra", "color": "green"};

localStorage.setItem('myStorage', JSON.stringify(obj));

And to retrieve the object later

var obj = JSON.parse(localStorage.getItem('myStorage'));

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

This issue is almost invariably a simple one. The code is bad. It's rarely the tools, just from a statistical analysis. Untold millions of people are using Visual Studio every day and maybe a few are using your code - which bit of code is getting the better testing? I guarantee that, if this were a problem with VS, we would probably already have found it.

What the statement means is that, when you try to access memory that isn't yours, it's usually because you're doing it with a corrupted pointer, that came from somewhere else. That's why it's stating the indication.

With memory corruption, the catching of the error is rarely near the root cause of the error. And the effects are exactly what you describe, seemingly random. You'll just have to look at the usual culprits, things like:

  • uninitialised pointers or other values.
  • writing more to a buffer than its size.
  • resources shared by threads that aren't protected by mutexes.

Working backwards from a problem like this to find the root cause is incredibly difficult given that so much could have happened between the creation of the problem and the detection of the problem.

I mostly find it's easier to have a look at what is corrupt (say, a specific pointer) and then do manual static analysis of the code to see what could have corrupted it, checking for the usual culprits as shown above. However, even this won't catch long chains of problems.

I'm not familiar enough with VS to know but you may also want to look into the possibility of using a memory tracking tool (like valgrind for Linux) to see if it can spot any obvious issues.

What's the common practice for enums in Python?

I've seen this pattern several times:

>>> class Enumeration(object):
        def __init__(self, names):  # or *names, with no .split()
            for number, name in enumerate(names.split()):
                setattr(self, name, number)

>>> foo = Enumeration("bar baz quux")
>>> foo.quux
2

You can also just use class members, though you'll have to supply your own numbering:

>>> class Foo(object):
        bar  = 0
        baz  = 1
        quux = 2

>>> Foo.quux
2

If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.

How can I check the system version of Android?

I can't comment on the answers, but there is a huge mistake in Kaushik's answer: SDK_INT is not the same as system version but actually refers to API Level.

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
    //this code will be executed on devices running ICS or later
}

The value Build.VERSION_CODES.ICE_CREAM_SANDWICH equals 14. 14 is the API level of Ice Cream Sandwich, while the system version is 4.0. So if you write 4.0, your code will be executed on all devices starting from Donut, because 4 is the API level of Donut (Build.VERSION_CODES.DONUT equals 4).

if(Build.VERSION.SDK_INT >= 4.0){
    //this code will be executed on devices running on DONUT (NOT ICS) or later
}

This example is a reason why using 'magic number' is a bad habit.

Getting 404 Not Found error while trying to use ErrorDocument

The ErrorDocument directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot. In your case, this means that the actual path to the ErrorDocument is

ErrorDocument 404 /hellothere/error/404page.html

How to check if string input is a number?

Here is the simplest solution:

a= input("Choose the option\n")

if(int(a)):
    print (a);
else:
    print("Try Again")

text-overflow: ellipsis not working

Add the Following lines in CSS for ellipsis to work

 p {
     display: block; // change it as per your requirement
     overflow: hidden;
     text-overflow: ellipsis;
     white-space: nowrap;
   }

Custom format for time command

You could use the date command to get the current time before and after performing the work to be timed and calculate the difference like this:

#!/bin/bash

# Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC)
T="$(date +%s)"

# Do some work here
sleep 2

T="$(($(date +%s)-T))"
echo "Time in seconds: ${T}"

printf "Pretty format: %02d:%02d:%02d:%02d\n" "$((T/86400))" "$((T/3600%24))" "$((T/60%60))" "$((T%60))""

Notes: $((...)) can be used for basic arithmetic in bash – caution: do not put spaces before a minus - as this might be interpreted as a command-line option.

See also: http://tldp.org/LDP/abs/html/arithexp.html

EDIT:
Additionally, you may want to take a look at sed to search and extract substrings from the output generated by time.

EDIT:

Example for timing with milliseconds (actually nanoseconds but truncated to milliseconds here). Your version of date has to support the %N format and bash should support large numbers.

# UNIX timestamp concatenated with nanoseconds
T="$(date +%s%N)"

# Do some work here
sleep 2

# Time interval in nanoseconds
T="$(($(date +%s%N)-T))"
# Seconds
S="$((T/1000000000))"
# Milliseconds
M="$((T/1000000))"

echo "Time in nanoseconds: ${T}"
printf "Pretty format: %02d:%02d:%02d:%02d.%03d\n" "$((S/86400))" "$((S/3600%24))" "$((S/60%60))" "$((S%60))" "${M}"

DISCLAIMER:
My original version said

M="$((T%1000000000/1000000))"

but this was edited out because it apparently did not work for some people whereas the new version reportedly did. I did not approve of this because I think that you have to use the remainder only but was outvoted.
Choose whatever fits you.

@ViewChild in *ngIf

I think using defer from lodash makes a lot of sense especially in my case where my @ViewChild() was inside async pipe

Convert a character digit to the corresponding integer in C

Here are helper functions which allow to convert digit in char to int and vice versa:

int toInt(char c) {
    return c - '0';
}

char toChar(int i) {
    return i + '0';
}

How do you add UI inside cells in a google spreadsheet using app script?

Status 2018:

There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.


This being said, there are some things that you can indeed do:

You can...

You can place images within cells using IMAGE(URL), but they cannot be linked to Apps Script functions.

You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))

You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.

handling DATETIME values 0000-00-00 00:00:00 in JDBC

If, after adding lines:

<property
name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>

hibernate.connection.zeroDateTimeBehavior=convertToNull

<connection-property
name="zeroDateTimeBehavior">convertToNull</connection-property>

continues to be an error:

Illegal DATETIME, DATE, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00 00:00:00' or '0000-00-00').

find lines:

1) resultSet.getTime("time"); // time = 00:00:00
2) resultSet.getTimestamp("timestamp"); // timestamp = 00000000000000
3) resultSet.getDate("date"); // date = 0000-00-00 00:00:00

replace with the following lines, respectively:

1) Time.valueOf(resultSet.getString("time"));
2) Timestamp.valueOf(resultSet.getString("timestamp"));
3) Date.valueOf(resultSet.getString("date"));

Missing styles. Is the correct theme chosen for this layout?

You can simply remove this error through change "App theme" and select any theme such as light. This error will be removed.

Move textfield when keyboard appears swift

    func registerForKeyboardNotifications(){
        //Keyboard
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWasShown), name: UIKeyboardDidShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIKeyboardDidHideNotification, object: nil)


    }
    func deregisterFromKeyboardNotifications(){

        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)

    }
    func keyboardWasShown(notification: NSNotification){

        let userInfo: NSDictionary = notification.userInfo!
        let keyboardInfoFrame = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue()

        let windowFrame:CGRect = (UIApplication.sharedApplication().keyWindow!.convertRect(self.view.frame, fromView:self.view))

        let keyboardFrame = CGRectIntersection(windowFrame, keyboardInfoFrame!)

        let coveredFrame = UIApplication.sharedApplication().keyWindow!.convertRect(keyboardFrame, toView:self.view)

        let contentInsets = UIEdgeInsetsMake(0, 0, (coveredFrame.size.height), 0.0)
        self.scrollViewInAddCase .contentInset = contentInsets;
        self.scrollViewInAddCase.scrollIndicatorInsets = contentInsets;
        self.scrollViewInAddCase.contentSize = CGSizeMake((self.scrollViewInAddCase.contentSize.width), (self.scrollViewInAddCase.contentSize.height))

    }
    /**
     this method will fire when keyboard was hidden

     - parameter notification: contains keyboard details
     */
    func keyboardWillBeHidden (notification: NSNotification) {

        self.scrollViewInAddCase.contentInset = UIEdgeInsetsZero
        self.scrollViewInAddCase.scrollIndicatorInsets = UIEdgeInsetsZero

    }

Importing project into Netbeans

Since you already have all the files in a folder, say "Project", you simply have to open Netbeans and go to File -> Open Project (or Ctrl + Shift+ O on Windows) and then from the dialog box navigate to the folder containing the Folder "Project".

You will see in the dialog box of Netbeans a 'Java cup'. Well, that's your project.

Fitting a density curve to a histogram in R

I had the same problem but Dirk's solution didn't seem to work. I was getting this warning messege every time

"prob" is not a graphical parameter

I read through ?hist and found about freq: a logical vector set TRUE by default.

the code that worked for me is

hist(x,freq=FALSE)
lines(density(x),na.rm=TRUE)

Maven: Failed to read artifact descriptor

For me , it was related to setting the "User Setting.xml" inside

Window > preferences > Maven > User Settings > and then browsing to the user Settings inside the { maven unarchived directory / }/apache-maven-2.2.1/conf/settings.xml . 

JavaScript check if value is only undefined, null or false

Another solution:

Based on the document, Boolean object will return true if the value is not 0, undefined, null, etc. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

So

if(Boolean(val))
{
//executable...
}

Where can I find a list of keyboard keycodes?

I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).

Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

Which exception should I raise on bad/illegal argument combinations in Python?

I would inherit from ValueError

class IllegalArgumentError(ValueError):
    pass

It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.

If you need to catch that specific error, it is helpful to have a name.

Retrieve a Fragment from a ViewPager

Create integer resource id in /values/integers.xml

<integer name="page1">1</integer>
<integer name="page2">2</integer>
<integer name="page3">3</integer>

Then in PagerAdapter getItem function:

public Fragment getItem(int position) {

        Fragment fragment = null;

        if (position == 0) {
            fragment = FragmentOne.newInstance();
            mViewPager.setTag(R.integer.page1,fragment);

        }
        else if (position == 1) {

            fragment = FragmentTwo.newInstance();
            mViewPager.setTag(R.integer.page2,fragment);

        } else if (position == 2) {

            fragment = FragmentThree.newInstance();
            mViewPager.setTag(R.integer.page3,fragment);

        }

        return fragment;
        }

Then in activity write this function to get fragment reference:

private Fragment getFragmentByPosition(int position) {
    Fragment fragment = null;

    switch (position) {
        case 0:
            fragment = (Fragment) mViewPager.getTag(R.integer.page1);
            break;

        case 1:

            fragment = (Fragment) mViewPager.getTag(R.integer.page2);
            break;

        case 2:
            fragment = (Fragment) mViewPager.getTag(R.integer.page3);
            break;
            }

            return fragment;
    }

Get the fragment reference by calling the above function and then cast it to your custom fragment:

Fragment fragment = getFragmentByPosition(position);

        if (fragment != null) {
                    FragmentOne fragmentOne = (FragmentOne) fragment;
                    }

Converting a Date object to a calendar object

Here's your method:

public static Calendar toCalendar(Date date){ 
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  return cal;
}

Everything else you are doing is both wrong and unnecessary.

BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).


OK, let's milk your code, shall we?

DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString()); 

DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?

Better way to sort array in descending order

Sure, You can customize the sort.

You need to give the Sort() a delegate to a comparison method which it will use to sort.

Using an anonymous method:

Array.Sort<int>( array,
delegate(int a, int b)
  {
    return b - a; //Normal compare is a-b
  }); 

Read more about it:

Sorting arrays
MSDN - Array.Sort Method (T[], Comparison)

XML Error: There are multiple root elements

Wrap the xml in another element

<wrapper>
<parent>
    <child>
        Text
    </child>
</parent>
<parent>
    <child>
        <grandchild>
            Text
        </grandchild>
        <grandchild>
            Text
        </grandchild>
    </child>
    <child>
        Text
    </child>
</parent>
</wrapper>

Drop all tables whose names begin with a certain string

CREATE PROCEDURE usp_GenerateDROP
    @Pattern AS varchar(255)
    ,@PrintQuery AS bit
    ,@ExecQuery AS bit
AS
BEGIN
    DECLARE @sql AS varchar(max)

    SELECT @sql = COALESCE(@sql, '') + 'DROP TABLE [' + TABLE_NAME + ']' + CHAR(13) + CHAR(10)
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME LIKE @Pattern

    IF @PrintQuery = 1 PRINT @sql
    IF @ExecQuery = 1 EXEC (@sql)
END

How do I do top 1 in Oracle?

SELECT *
  FROM (SELECT * FROM MyTbl ORDER BY Fname )
 WHERE ROWNUM = 1;

MySql difference between two timestamps in days?

If you're happy to ignore the time portion in the columns, DATEDIFF() will give you the difference you're looking for in days.

SELECT DATEDIFF('2010-10-08 18:23:13', '2010-09-21 21:40:36') AS days;
+------+
| days |
+------+
|   17 |
+------+

Need to get a string after a "word" in a string in c#

string toBeSearched = "code : ";
string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Length);

Something like this?

Perhaps you should handle the case of missing code :...

string toBeSearched = "code : ";
int ix = myString.IndexOf(toBeSearched);

if (ix != -1) 
{
    string code = myString.Substring(ix + toBeSearched.Length);
    // do something here
}

Difference between application/x-javascript and text/javascript content types

mime-types starting with x- are not standardized. In case of javascript it's kind of outdated. Additional the second code snippet

<?Header('Content-Type: text/javascript');?>

requires short_open_tags to be enabled. you should avoid it.

<?php Header('Content-Type: text/javascript');?>

However, the completely correct mime-type for javascript is

application/javascript

http://www.iana.org/assignments/media-types/application/index.html

change values in array when doing foreach

Array: [1, 2, 3, 4]
Result: ["foo1", "foo2", "foo3", "foo4"]

Array.prototype.map() Keep original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
const modifiedArr = originalArr.map(name => `${name}man`);

console.log( "Original: %s", originalArr );
console.log( "Modified: %s", modifiedArr );
_x000D_
_x000D_
_x000D_

Array.prototype.forEach() Override original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
originalArr.forEach((name, index) => originalArr[index] = `${name}man`);

console.log( "Overridden: %s", originalArr );
_x000D_
_x000D_
_x000D_

Compiler warning - suggest parentheses around assignment used as truth value

Be explicit - then the compiler won't warn that you perhaps made a mistake.

while ( (list = list->next) != NULL )

or

while ( (list = list->next) )

Some day you'll be glad the compiler told you, people do make that mistake ;)

How can I show a hidden div when a select option is selected?

Being more generic, passing values from calling element (which is easier to maintain).

  • Specify the start condition in the text field (display:none)
  • Pass the required option value to show/hide on ("Other")
  • Pass the target and field to show/hide ("TitleOther")

_x000D_
_x000D_
function showHideEle(selectSrc, targetEleId, triggerValue) { _x000D_
 if(selectSrc.value==triggerValue) {_x000D_
  document.getElementById(targetEleId).style.display = "inline-block";_x000D_
 } else {_x000D_
  document.getElementById(targetEleId).style.display = "none";_x000D_
 }_x000D_
} 
_x000D_
<select id="Title"_x000D_
   onchange="showHideEle(this, 'TitleOther', 'Other')">_x000D_
      <option value="">-- Choose</option>_x000D_
      <option value="Mr">Mr</option>_x000D_
      <option value="Mrs">Mrs</option>_x000D_
      <option value="Miss">Miss</option>_x000D_
      <option value="Other">Other --&gt;</option>      _x000D_
</select>_x000D_
<input id="TitleOther" type="text" title="Title other" placeholder="Other title" _x000D_
    style="display:none;"/>
_x000D_
_x000D_
_x000D_

React PropTypes : Allow different types of PropTypes for one prop

Here is pro example of using multi proptypes and single proptype.

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Basically, you get connections in the Sleep state when :

  • a PHP script connects to MySQL
  • some queries are executed
  • then, the PHP script does some stuff that takes time
    • without disconnecting from the DB
  • and, finally, the PHP script ends
    • which means it disconnects from the MySQL server

So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.

A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.


Another thing, that I often see when there is some load on the server :

  • There are more and more requests coming to Apache
    • which means many pages to generate
  • Each PHP script, in order to generate a page, connects to the DB and does some queries
  • These queries take more and more time, as the load on the DB server increases
  • Which means more processes keep stacking up

A solution that can help is to reduce the time your queries take -- optimizing the longest ones.

What is the Simplest Way to Reverse an ArrayList?

Reversing a ArrayList in a recursive way and without creating a new list for adding elements :

   public class ListUtil {

    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
        arrayList.add("4");
        arrayList.add("5");
        System.out.println("Reverse Order: " + reverse(arrayList));

    }

    public static <T> List<T> reverse(List<T> arrayList) {
        return reverse(arrayList,0,arrayList.size()-1);
    }
    public static <T> List<T> reverse(List<T> arrayList,int startIndex,int lastIndex) {

        if(startIndex<lastIndex) {
            T t=arrayList.get(lastIndex);
            arrayList.set(lastIndex,arrayList.get(startIndex));
            arrayList.set(startIndex,t);
            startIndex++;
            lastIndex--;
            reverse(arrayList,startIndex,lastIndex);
        }
        return arrayList;
    }

}

CSS :: child set to change color on parent hover, but changes also when hovered itself

If you don't care about supporting old browsers, you can use :not() to exclude that element:

.parent:hover span:not(:hover) {
    border: 10px solid red;
}

Demo: http://jsfiddle.net/vz9A9/1/

If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:

.parent span:hover {
    border: 10px solid green;
}

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

Here is my experience and Solution. I didn't touched code

  1. Select view (UILabel, UIImage etc)
  2. Editor > Pin > (Select...) to Superview
  3. Editor > Resolve Auto Layout Issues > Add Missing Constraints

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

Keyboard shortcut to change font size in Eclipse?

The Eclipse-Fonts extension will add toolbar buttons and keyboard shortcuts for changing font size. You can then use AutoHotkey to make Ctrl+Mousewheel zoom.

Under Help | Install New Software... in the menu, paste the update URL (http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/) into the Works with: text box and press Enter. Expand the tree and select FontsFeature as in the following image:

Eclipse extension installation screen capture

Complete the installation and restart Eclipse, then you should see the A toolbar buttons (circled in red in the following image) and be able to use the keyboard shortcuts Ctrl+- and Ctrl+= to zoom (although you may have to unbind those keys from Eclipse first).

Eclipse screen capture with the font size toolbar buttons circled

To get Ctrl+MouseWheel zooming, you can use AutoHotkey with the following script:

; Ctrl+MouseWheel zooming in Eclipse.
; Requires Eclipse-Fonts (https://code.google.com/p/eclipse-fonts/).
; Thank you for the unique window class, SWT/Eclipse.
#IfWinActive ahk_class SWT_Window0
    ^WheelUp:: Send ^{=}
    ^WheelDown:: Send ^-
#IfWinActive

Why is document.write considered a "bad practice"?

Pro:

  • It's the easiest way to embed inline content from an external (to your host/domain) script.
  • You can overwrite the entire content in a frame/iframe. I used to use this technique a lot for menu/navigation pieces before more modern Ajax techniques were widely available (1998-2002).

Con:

  • It serializes the rendering engine to pause until said external script is loaded, which could take much longer than an internal script.
  • It is usually used in such a way that the script is placed within the content, which is considered bad-form.

URL encoding in Android

Also you can use this

private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);

it's the most simple method

Storing Form Data as a Session Variable

You can solve this problem using this code:

if(!empty($_GET['variable from which you get'])) 
{
$_SESSION['something']= $_GET['variable from which you get'];
}

So you get the variable from a GET form, you will store in the $_SESSION['whatever'] variable just once when $_GET['variable from which you get']is set and if it is empty $_SESSION['something'] will store the old parameter

How do I set the proxy to be used by the JVM

reading an XML file and needs to download its schema

If you are counting on retrieving schemas or DTDs over the internet, you're building a slow, chatty, fragile application. What happens when that remote server hosting the file takes planned or unplanned downtime? Your app breaks. Is that OK?

See http://xml.apache.org/commons/components/resolver/resolver-article.html#s.catalog.files

URL's for schemas and the like are best thought of as unique identifiers. Not as requests to actually access that file remotely. Do some google searching on "XML catalog". An XML catalog allows you to host such resources locally, resolving the slowness, chattiness and fragility.

It's basically a permanently cached copy of the remote content. And that's OK, since the remote content will never change. If there's ever an update, it'd be at a different URL. Making the actual retrieval of the resource over the internet especially silly.

How to master AngularJS?

This is the most comprehensive AngularJS learning resource repository I've come across:

AngularJS-Learning

To pluck out the best parts (in recommended order of learning):

jQuery Ajax File Upload

var dataform = new FormData($("#myform")[0]);
//console.log(dataform);
$.ajax({
    url: 'url',
    type: 'POST',
    data: dataform,
    async: false,
    success: function(res) {
        response data;
    },
    cache: false,
    contentType: false,
    processData: false
});

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

How to attach a process in gdb

Try one of these:

gdb -p 12271
gdb /path/to/exe 12271

gdb /path/to/exe
(gdb) attach 12271

Git Pull is Not Possible, Unmerged Files

Ryan Stewart's answer was almost there. In the case where you actually don't want to delete your local changes, there's a workflow you can use to merge:

  • Run git status. It will give you a list of unmerged files.
  • Merge them (by hand, etc.)
  • Run git commit

Git will commit just the merges into a new commit. (In my case, I had additional added files on disk, which weren't lumped into that commit.)

Git then considers the merge successful and allows you to move forward.

Why do I keep getting Delete 'cr' [prettier/prettier]?

I am using git+vscode+windows+vue, and after read the eslint document: https://eslint.org/docs/rules/linebreak-style

Finally fix it by:

add *.js text eol=lf to .gitattributes

then run vue-cli-service lint --fix

How can I use "." as the delimiter with String.split() in java

The argument to split is a regular expression. The period is a regular expression metacharacter that matches anything, thus every character in line is considered to be a split character, and is thrown away, and all of the empty strings between them are thrown away (because they're empty strings). The result is that you have nothing left.

If you escape the period (by adding an escaped backslash before it), then you can match literal periods. (line.split("\\."))

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

For Linux just make a symlink, like this:

ln -s /android/android-studio/plugins/android/lib/templates /android/sdk/tools/templates

Applying styles to tables with Twitter Bootstrap

Bootstrap offers various table styles. Have a look at Base CSS - Tables for documentation and examples.

The following style gives great looking tables:

<table class="table table-striped table-bordered table-condensed">
  ...
</table>

Azure SQL Database "DTU percentage" metric

A DTU is a unit of measure for the performance of a service tier and is a summary of several database characteristics. Each service tier has a certain number of DTUs assigned to it as an easy way to compare the performance level of one tier versus another.

Database Throughput Unit (DTU): DTUs provide a way to describe the relative capacity of a performance level of Basic, Standard, and Premium databases. DTUs are based on a blended measure of CPU, memory, reads, and writes. As DTUs increase, the power offered by the performance level increases. For example, a performance level with 5 DTUs has five times more power than a performance level with 1 DTU. A maximum DTU quota applies to each server.

The DTU Quota applies to the server, not the individual databases and each server has a maximum of 1600 DTUs. The DTU% is the percentage of units your particular database is using and it seems that this number can go over 100% of the DTU rating of the service tier (I assume to the limit of the server). This percentage number is designed to help you choose the appropriate service tier.

From down toward the bottom of this announcement:

For example, if your DTU consumption shows a value of 80%, it indicates it is consuming DTU at the rate of 80% of the limit an S2 database would have. If you see values greater than 100% in this view it means that you need a performance tier larger than S2.

As an example, let’s say you see a percentage value of 300%. This tells you that you are using three times more resources than would be available in an S2. To determine a reasonable starting size, compare the DTUs available in an S2 (50 DTUs) with the next higher sizes (P1 = 100 DTUs, or 200% of S2, P2 = 200 DTUs or 400% of S2). Because you are at 300% of S2 you would want to start with a P2 and re-test.

Should I use string.isEmpty() or "".equals(string)?

String.equals("") is actually a bit slower than just an isEmpty() call. Strings store a count variable initialized in the constructor, since Strings are immutable.

isEmpty() compares the count variable to 0, while equals will check the type, string length, and then iterate over the string for comparison if the sizes match.

So to answer your question, isEmpty() will actually do a lot less! and that's a good thing.

401 Unauthorized: Access is denied due to invalid credentials

I had a permissions issue to a website and just couldn't get Windows authentication to work. It was a folder permissions rather than ASP.NET configuration issue in the end and once the Everyone user was granted permissions it started working.

Is there a Google Chrome-only CSS hack?

Try to use the new '@supports' feature, here is one good hack that you might like:

* UPDATE!!! * Microsoft Edge and Safari 9 both added support for the @supports feature in Fall 2015, Firefox also -- so here is my updated version for you:

/* Chrome 29+ (Only) */

@supports (-webkit-appearance:none) and (not (overflow:-webkit-marquee))
and (not (-ms-ime-align:auto)) and (not (-moz-appearance:none)) { 
   .selector { color:red; } 
}

More info on this here (the reverse... Safari but not Chrome): [ is there a css hack for safari only NOT chrome? ]

The previous CSS Hack [before Edge and Safari 9 or newer Firefox versions]:

/* Chrome 28+ (now also Microsoft Edge, Firefox, and Safari 9+) */

@supports (-webkit-appearance:none) { .selector { color:red; } }

This worked for (only) chrome, version 28 and newer.

(The above chrome 28+ hack was not one of my creations. I found this on the web and since it was so good I sent it to BrowserHacks.com recently, there are others coming.)

August 17th, 2014 update: As I mentioned, I have been working on reaching more versions of chrome (and many other browsers), and here is one I crafted that handles chrome 35 and newer.

/* Chrome 35+ */

_::content, _:future, .selector:not(*:root) { color:red; }

In the comments below it was mentioned by @BoltClock about future, past, not... etc... We can in fact use them to go a little farther back in Chrome history.

So then this is one that also works but not 'Chrome-only' which is why I did not put it here. You still have to separate it by a Safari-only hack to complete the process. I have created css hacks to do this however, not to worry. Here are a few of them, starting with the simplest:

/* Chrome 26+, Safari 6.1+ */

_:past, .selector:not(*:root) { color:red; }

Or instead, this one which goes back to Chrome 22 and newer, but Safari as well...

/* Chrome 22+, Safari 6.1+ */

@media screen and (-webkit-min-device-pixel-ratio:0)
and (min-resolution:.001dpcm),
screen and(-webkit-min-device-pixel-ratio:0)
{
    .selector { color:red; } 
}

The block of Chrome versions 22-28 (more complicated but works nicely) are also possible to target via a combination I worked out:

/* Chrome 22-28 (Only!) */

@media screen and(-webkit-min-device-pixel-ratio:0)
{
    .selector  {-chrome-:only(;

       color:red; 

    );}
}

Now follow up with this next couple I also created that targets Safari 6.1+ (only) in order to still separate Chrome and Safari. Updated to include Safari 8

/* Safari 6.1-7.0 */

@media screen and (-webkit-min-device-pixel-ratio:0) and (min-color-index:0)
{
    .selector {(;  color:blue;  );} 
}


/* Safari 7.1+ */

_::-webkit-full-page-media, _:future, :root .selector { color:blue; } 

So if you put one of the Chrome+Safari hacks above, and then the Safari 6.1-7 and 8 hacks in your styles sequentially, you will have Chrome items in red, and Safari items in blue.

Finding element in XDocument?

The Elements() method returns an IEnumerable<XElement> containing all child elements of the current node. For an XDocument, that collection only contains the Root element. Therefore the following is required:

var query = from c in xmlFile.Root.Elements("Band")
            select c;

How should I store GUID in MySQL tables?

I would suggest using the functions below since the ones mentioned by @bigh_29 transforms my guids into new ones (for reasons I don't understand). Also, these are a little bit faster in the tests I did on my tables. https://gist.github.com/damienb/159151

DELIMITER |

CREATE FUNCTION uuid_from_bin(b BINARY(16))
RETURNS CHAR(36) DETERMINISTIC
BEGIN
  DECLARE hex CHAR(32);
  SET hex = HEX(b);
  RETURN LOWER(CONCAT(LEFT(hex, 8), '-', MID(hex, 9,4), '-', MID(hex, 13,4), '-', MID(hex, 17,4), '-', RIGHT(hex, 12)));
END
|

CREATE FUNCTION uuid_to_bin(s CHAR(36))
RETURNS BINARY(16) DETERMINISTIC
RETURN UNHEX(CONCAT(LEFT(s, 8), MID(s, 10, 4), MID(s, 15, 4), MID(s, 20, 4), RIGHT(s, 12)))
|

DELIMITER ;

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

load and execute order of scripts

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.

There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.

When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.

A script tag with async may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async is that it can run anytime and that time is not predictable.

A script tag with defer waits until the entire parser is done and then runs all scripts marked with defer in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer or async.

Here's a quote from that article:

script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.

The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.

A quote from the HTML5 spec:

Then, the first of the following options that describes the situation must be followed:

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

Remove the first element from this list of scripts that will execute in order as soon as possible.

If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.


What about Javascript module scripts, type="module"?

Javascript now has support for module loading with syntax like this:

<script type="module">
  import {addTextToBody} from './utils.mjs';

  addTextToBody('Modules are pretty cool.');
</script>

Or, with src attribute:

<script type="module" src="http://somedomain.com/somescript.mjs">
</script>

All scripts with type="module" are automatically given the defer attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.

Module scripts can also be given the async attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async script in any particular order relative to other scripts.

There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.

Sys is undefined

I found the error when using a combination of the Ajax Control Toolkit ToolkitScriptManager and URL Write 2.0.

In my <rewrite> <outboundRules> I had a precondition:

<preConditions>
    <preCondition name="IsHTML">
        <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html"/>
    </preCondition>
</preConditions>

But apparently some of my outbound rules weren't set to use the precondition.

Once I had that preCondition set on all my outbound rules:

<rule preCondition="IsHTML" name="MyOutboundRule">

No more problem.

Convert/cast an stdClass object to another class

Convert it to an array, return the first element of that array, and set the return param to that class. Now you should get the autocomplete for that class as it will regconize it as that class instead of stdclass.

/**
 * @return Order
 */
    public function test(){
    $db = new Database();

    $order = array();
    $result = $db->getConnection()->query("select * from `order` where productId in (select id from product where name = 'RTX 2070')");
    $data = $result->fetch_object("Order"); //returns stdClass
    array_push($order, $data);

    $db->close();
    return $order[0];
}

How to strip a specific word from a string?

If want to remove the word from only the start of the string, then you could do:

  string[string.startswith(prefix) and len(prefix):]  

Where string is your string variable and prefix is the prefix you want to remove from your string variable.

For example:

  >>> papa = "papa is a good man. papa is the best."  
  >>> prefix = 'papa'
  >>> papa[papa.startswith(prefix) and len(prefix):]
  ' is a good man. papa is the best.'

SQL query for a carriage return in a string and ultimately removing carriage return

If you are considering creating a function, try this: DECLARE @schema sysname = 'dbo' , @tablename sysname = 'mvtEST' , @cmd NVarchar(2000) , @ColName sysname

    DECLARE @NewLine Table
    (ColumnName Varchar(100)
    ,Location Int
    ,ColumnValue Varchar(8000)
    )

    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'

    DECLARE looper CURSOR FAST_FORWARD for
    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'
    OPEN looper
    FETCH NEXT FROM looper INTO @ColName

    WHILE @@fetch_status = 0
    BEGIN
    SELECT @cmd = 'select ''' +@ColName+    ''',  CHARINDEX(Char(10),  '+  @ColName +') , '+ @ColName + ' from '+@schema + '.'+@tablename +' where CHARINDEX(Char(10),  '+  @ColName +' ) > 0 or CHARINDEX(CHAR(13), '+@ColName +') > 0'
    PRINT @cmd
    INSERT @NewLine ( ColumnName, Location, ColumnValue )
    EXEC sp_executesql @cmd
    FETCH NEXT FROM looper INTO @ColName
    end
    CLOSE looper
    DEALLOCATE looper


    SELECT * FROM  @NewLine

How To Create Table with Identity Column

[id] [int] IDENTITY(1,1) NOT NULL,

of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

enter image description here

How to stop a PowerShell script on the first error?

Redirecting stderr to stdout seems to also do the trick without any other commands/scriptblock wrappers although I can't find an explanation why it works that way..

# test.ps1

$ErrorActionPreference = "Stop"

aws s3 ls s3://xxx
echo "==> pass"

aws s3 ls s3://xxx 2>&1
echo "shouldn't be here"

This will output the following as expected (the command aws s3 ... returns $LASTEXITCODE = 255)

PS> .\test.ps1

An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied
==> pass

How do I test if a variable does not equal either of two values?

I do that using jQuery

if ( 0 > $.inArray( test, [a,b] ) ) { ... }

How do you append rows to a table using jQuery?

I'm assuming you want to add this row to the <tbody> element, and simply using append() on the <table> will insert the <tr> outside the <tbody>, with perhaps undesirable results.

$('a').click(function() {
   $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
});

EDIT: Here is the complete source code, and it does indeed work: (Note the $(document).ready(function(){});, which was not present before.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('a').click(function() {
       $('#myTable tbody').append('<tr class="child"><td>blahblah</td></tr>');
    });
});
</script>
<title></title>
</head>
<body>
<a href="javascript:void(0);">Link</a>
<table id="myTable">
  <tbody>
    <tr>
      <td>test</td>
    </tr>
  </tbody>
</table>
</body>
</html>

System.BadImageFormatException: Could not load file or assembly

Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:

Go and set your choice as shown:

Angular - Set headers for every request

Better late than never... =)

You may take the concept of extended BaseRequestOptions(from here https://angular.io/docs/ts/latest/guide/server-communication.html#!#override-default-request-options) and refresh the headers "on the fly" (not only in constructor). You may use getter/setter "headers" property override like this:

import { Injectable } from '@angular/core';
import { BaseRequestOptions, RequestOptions, Headers } from '@angular/http';

@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {

    private superHeaders: Headers;

    get headers() {
        // Set the default 'Content-Type' header
        this.superHeaders.set('Content-Type', 'application/json');

        const token = localStorage.getItem('authToken');
        if(token) {
            this.superHeaders.set('Authorization', `Bearer ${token}`);
        } else {
            this.superHeaders.delete('Authorization');
        }
        return this.superHeaders;
    }

    set headers(headers: Headers) {
        this.superHeaders = headers;
    }

    constructor() {
        super();
    }
}

export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };

Calling a function of a module by using its name (a string)

This is a simple answer, this will allow you to clear the screen for example. There are two examples below, with eval and exec, that will print 0 at the top after cleaning (if you're using Windows, change clear to cls, Linux and Mac users leave as is for example) or just execute it, respectively.

eval("os.system(\"clear\")")
exec("os.system(\"clear\")")

JNI and Gradle in Android Studio

Android Studio 2.2 came out with the ability to use ndk-build and cMake. Though, we had to wait til 2.2.3 for the Application.mk support. I've tried it, it works...though, my variables aren't showing up in the debugger. I can still query them via command line though.

You need to do something like this:

externalNativeBuild{
   ndkBuild{
        path "Android.mk"
    }
}

defaultConfig {
  externalNativeBuild{
    ndkBuild {
      arguments "NDK_APPLICATION_MK:=Application.mk"
      cFlags "-DTEST_C_FLAG1"  "-DTEST_C_FLAG2"
      cppFlags "-DTEST_CPP_FLAG2"  "-DTEST_CPP_FLAG2"
      abiFilters "armeabi-v7a", "armeabi"
    }
  } 
}

See http://tools.android.com/tech-docs/external-c-builds

NB: The extra nesting of externalNativeBuild inside defaultConfig was a breaking change introduced with Android Studio 2.2 Preview 5 (July 8, 2016). See the release notes at the above link.

how to disable DIV element and everything inside

pure javascript no jQuery

_x000D_
_x000D_
function sah() {_x000D_
  $("#div2").attr("disabled", "disabled").off('click');_x000D_
  var x1=$("#div2").hasClass("disabledDiv");_x000D_
  _x000D_
  (x1==true)?$("#div2").removeClass("disabledDiv"):$("#div2").addClass("disabledDiv");_x000D_
  sah1(document.getElementById("div1"));_x000D_
_x000D_
}_x000D_
_x000D_
    function sah1(el) {_x000D_
        try {_x000D_
            el.disabled = el.disabled ? false : true;_x000D_
        } catch (E) {}_x000D_
        if (el.childNodes && el.childNodes.length > 0) {_x000D_
            for (var x = 0; x < el.childNodes.length; x++) {_x000D_
                sah1(el.childNodes[x]);_x000D_
            }_x000D_
        }_x000D_
    }
_x000D_
#div2{_x000D_
  padding:5px 10px;_x000D_
  background-color:#777;_x000D_
  width:150px;_x000D_
  margin-bottom:20px;_x000D_
}_x000D_
.disabledDiv {_x000D_
    pointer-events: none;_x000D_
    opacity: 0.4;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
        <div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
        <input type="text" value="SAH Computer" />_x000D_
        <br />_x000D_
        <input type="button" value="SAH Computer" />_x000D_
        <br />_x000D_
        <input type="radio" name="sex" value="Male" />Male_x000D_
        <Br />_x000D_
        <input type="radio" name="sex" value="Female" />Female_x000D_
        <Br />_x000D_
    </div>_x000D_
    <Br />_x000D_
    <Br />_x000D_
    <input type="button" value="Click" onclick="sah()" />
_x000D_
_x000D_
_x000D_

What does it mean to write to stdout in C?

It depends.

When you commit to sending output to stdout, you're basically leaving it up to the user to decide where that output should go.

If you use printf(...) (or the equivalent fprintf(stdout, ...)), you're sending the output to stdout, but where that actually ends up can depend on how I invoke your program.

If I launch your program from my console like this, I'll see output on my console:

$ prog
Hello, World! # <-- output is here on my console

However, I might launch the program like this, producing no output on the console:

$ prog > hello.txt

but I would now have a file "hello.txt" with the text "Hello, World!" inside, thanks to the shell's redirection feature.

Who knows – I might even hook up some other device and the output could go there. The point is that when you decide to print to stdout (e.g. by using printf()), then you won't exactly know where it will go until you see how the process is launched or used.

Relative div height

add this to you CSS:

html, body
{
    height: 100%;
}

working Fiddle

when you say to wrap to be 100%, 100% of what? of its parent (body), so his parent has to have some height.

and the same goes for body, his parent his html. html parent his the viewport.. so, by setting them both to 100%, wrap can also have a percentage height.

also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use

*
{
    padding: 0;
    margin: 0;
}

to disable that.

Look at That Fiddle

Untrack files from git temporarily

Use following command to untrack files

git rm --cached <file path>

numpy get index where value is true

To get the row numbers where at least one item is larger than 15:

>>> np.where(np.any(e>15, axis=1))
(array([1, 2], dtype=int64),)

How do I log errors and warnings into a file?

Simply put these codes at top of your PHP/index file:

error_reporting(E_ALL); // Error/Exception engine, always use E_ALL

ini_set('ignore_repeated_errors', TRUE); // always use TRUE

ini_set('display_errors', FALSE); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment

ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'your/path/to/errors.log'); // Logging file path

How can I pretty-print JSON using node.js?

Another workaround would be to make use of prettier to format the JSON. The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.

const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));

Extracting text OpenCV

Python Implementation for @dhanushka's solution:

def process_rgb(rgb):
    hasText = False
    gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
    morphKernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
    grad = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, morphKernel)
    # binarize
    _, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    # connect horizontally oriented regions
    morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
    connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, morphKernel)
    # find contours
    mask = np.zeros(bw.shape[:2], dtype="uint8")
    _,contours, hierarchy = cv2.findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    # filter contours
    idx = 0
    while idx >= 0:
        x,y,w,h = cv2.boundingRect(contours[idx])
        # fill the contour
        cv2.drawContours(mask, contours, idx, (255, 255, 255), cv2.FILLED)
        # ratio of non-zero pixels in the filled region
        r = cv2.contourArea(contours[idx])/(w*h)
        if(r > 0.45 and h > 5 and w > 5 and w > h):
            cv2.rectangle(rgb, (x,y), (x+w,y+h), (0, 255, 0), 2)
            hasText = True
        idx = hierarchy[0][idx][0]
    return hasText, rgb

Python Regex - How to Get Positions and Values of Matches

note that the span & group are indexed for multi capture groups in a regex

regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
    for idx in range(0, 4):
        print(match.span(idx), match.group(idx))

Could not create work tree dir 'example.com'.: Permission denied

I was facing the same issue but it was not a permission issue.

When you are doing git clone it will create try to create replica of the respository structure.

When its trying to create the folder/directory with same name and path in your local os process is not allowing to do so and hence the error. There was "background" java process running in Task-manager which was accessing the resource of the directory(folder) and hence it was showing as permission denied for git operations. I have killed those process and that solved my problem. Cheers!!

unsigned int vs. size_t

In short, size_t is never negative, and it maximizes performance because it's typedef'd to be the unsigned integer type that's big enough -- but not too big -- to represent the size of the largest possible object on the target platform.

Sizes should never be negative, and indeed size_t is an unsigned type. Also, because size_t is unsigned, you can store numbers that are roughly twice as big as in the corresponding signed type, because we can use the sign bit to represent magnitude, like all the other bits in the unsigned integer. When we gain one more bit, we are multiplying the range of numbers we can represents by a factor of about two.

So, you ask, why not just use an unsigned int? It may not be able to hold big enough numbers. In an implementation where unsigned int is 32 bits, the biggest number it can represent is 4294967295. Some processors, such as the IP16L32, can copy objects larger than 4294967295 bytes.

So, you ask, why not use an unsigned long int? It exacts a performance toll on some platforms. Standard C requires that a long occupy at least 32 bits. An IP16L32 platform implements each 32-bit long as a pair of 16-bit words. Almost all 32-bit operators on these platforms require two instructions, if not more, because they work with the 32 bits in two 16-bit chunks. For example, moving a 32-bit long usually requires two machine instructions -- one to move each 16-bit chunk.

Using size_t avoids this performance toll. According to this fantastic article, "Type size_t is a typedef that's an alias for some unsigned integer type, typically unsigned int or unsigned long, but possibly even unsigned long long. Each Standard C implementation is supposed to choose the unsigned integer that's big enough--but no bigger than needed--to represent the size of the largest possible object on the target platform."

Function return value in PowerShell

With PowerShell 5 we now have the ability to create classes. Change your function into a class, and return will only return the object immediately preceding it. Here is a real simple example.

class test_class {
    [int]return_what() {
        Write-Output "Hello, World!"
        return 808979
    }
}
$tc = New-Object -TypeName test_class
$tc.return_what()

If this was a function the expected output would be

Hello World
808979

but as a class the only thing returned is the integer 808979. A class is sort of like a guarantee that it will only return the type declared or void.

Display image at 50% of its "native" size

This should work:

img {
    max-width: 50%;
    height: auto;
}

Haversine Formula in Python (Bearing and Distance between two GPS points)

You can try the following:

from haversine import haversine
haversine((45.7597, 4.8422),(48.8567, 2.3508), unit='mi')
243.71209416020253

How to see top processes sorted by actual memory usage?

ps aux --sort '%mem'

from procps' ps (default on Ubuntu 12.04) generates output like:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
...
tomcat7   3658  0.1  3.3 1782792 124692 ?      Sl   10:12   0:25 /usr/lib/jvm/java-7-oracle/bin/java -Djava.util.logging.config.file=/var/lib/tomcat7/conf/logging.properties -D
root      1284  1.5  3.7 452692 142796 tty7    Ssl+ 10:11   3:19 /usr/bin/X -core :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch
ciro      2286  0.3  3.8 1316000 143312 ?      Sl   10:11   0:49 compiz
ciro      5150  0.0  4.4 660620 168488 pts/0   Sl+  11:01   0:08 unicorn_rails worker[1] -p 3000 -E development -c config/unicorn.rb             
ciro      5147  0.0  4.5 660556 170920 pts/0   Sl+  11:01   0:08 unicorn_rails worker[0] -p 3000 -E development -c config/unicorn.rb             
ciro      5142  0.1  6.3 2581944 239408 pts/0  Sl+  11:01   0:17 sidekiq 2.17.8 gitlab [0 of 25 busy]                                                                          
ciro      2386  3.6 16.0 1752740 605372 ?      Sl   10:11   7:38 /usr/lib/firefox/firefox

So here Firefox is the top consumer with 16% of my memory.

You may also be interested in:

ps aux --sort '%cpu'

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

Just go to https://www.lfd.uci.edu/~gohlke/pythonlibs/ find your suitable package (whl file). Download it. Go to the download folder in cmd or typing 'cmd' on the address bar of the folder. Run the command :

pip install mysqlclient-1.4.6-cp38-cp38-win32.whl

(Type the file name correctly. I have given an example only). Your problem will be solved without installing build toll cpp of 6GB size.

Escaping quotes and double quotes

In Powershell 5 escaping double quotes can be done by backtick (`). But sometimes you need to provide your double quotes escaped which can be done by backslash + backtick (\`). Eg in this curl call:

C:\Windows\System32\curl.exe -s -k -H "Content-Type: application/json" -XPOST localhost:9200/index_name/inded_type -d"{\`"velocity\`":3.14}"

get all the elements of a particular form

document.forms["form_name"].getElementsByTagName("input");

How to add items into a numpy array

Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.

That said, It's often unavoidable and the functions that do this are:

for 2-D arrays:

for 3-D arrays (the above plus):

for N-D arrays:

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.

class Person
  attr_accessor :age
  ...
end

Here, I can see that I may both read and write the age.

class Person
  attr_reader :age
  ...
end

Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.

But what is happening behind the scenes?

If you write:

attr_writer :age

That gets translated into:

def age=(value)
  @age = value
end

If you write:

attr_reader :age

That gets translated into:

def age
  @age
end

If you write:

attr_accessor :age

That gets translated into:

def age=(value)
  @age = value
end

def age
  @age
end

Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?

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

C:\\Users\\expoperialed\\Desktop\\Python This syntax worked for me.

How to redirect 'print' output to a file using python?

The easiest solution isn't through python; its through the shell. From the first line of your file (#!/usr/bin/python) I'm guessing you're on a UNIX system. Just use print statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead of

./script.py

to run the file, use

./script.py > <filename>

where you replace <filename> with the name of the file you want the output to go in to. The > token tells (most) shells to set stdout to the file described by the following token.

One important thing that needs to be mentioned here is that "script.py" needs to be made executable for ./script.py to run.

So before running ./script.py,execute this command

chmod a+x script.py (make the script executable for all users)

How to click or tap on a TextView text

You can set the click handler in xml with these attribute:

android:onClick="onClick"
android:clickable="true"

Don't forget the clickable attribute, without it, the click handler isn't called.

main.xml

    ...

    <TextView 
       android:id="@+id/click"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"               
       android:text="Click Me"
       android:textSize="55sp"
       android:onClick="onClick"                
       android:clickable="true"/>
    ...

MyActivity.java

       public class MyActivity extends Activity {

          public void onClick(View v) {
            ...
          }  
       }

Generating random numbers with normal distribution in Excel

Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.

How to correctly use "section" tag in HTML5?

The correct method is #2. You used the section tag to define a section of your document. From the specs http://www.w3.org/TR/html5/sections.html:

The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead

A cycle was detected in the build path of project xxx - Build Path Problem

When we have multiple projects in workspace, we have to set the references between the projects, not among the projects. If P1 references P2, P2 references P3, and P3 reference back to P1. That will cause a cycle.

The Solution is to draw a Diagram of the reference between projects in workspace. Check the Java Build Path of each of the projects to see the Tab of the Projects window. Take out the Project that are refering back to the main project, e.g. P3 references P1, in this example above.

Detailed operation is to select P3 project in RAD OR eclipse, right click on the project and choose the properties option, it brings up a new window for properties of P3. Click on the "Java Build Path" section, Choose the "Projects" option Tab. You can see the P3 has referenced P1 in the field. Select the P1 reference, click "Remove" button on the right side of the window. Then, click okay. The IDE will start to reset the path automatically.

Done.

Keep find all of the mis-referenced reference in every each projects until you have the right references to each of the projects in your Diagram. Good Luck!

AngularJS is rendering <br> as text not as a newline

I've used like this

function chatSearchCtrl($scope, $http,$sce) {
 // some more my code

// take this 
data['message'] = $sce.trustAsHtml(data['message']);

$scope.searchresults = data;

and in html I did

<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>

thats it I get my <br/> tag rendered

How can I join elements of an array in Bash?

Thanks @gniourf_gniourf for detailed comments on my combination of best worlds so far. Sorry for posting code not thoroughly designed and tested. Here is a better try.

# join with separator
join_ws() { local d=$1 s=$2; shift 2 && printf %s "$s${@/#/$d}"; }

This beauty by conception is

  • (still) 100% pure bash ( thanks for explicitly pointing out that printf is a builtin as well. I wasn't aware about this before ... )
  • works with multi-character delimiters
  • more compact and more complete and this time carefully thought over and long-term stress-tested with random substrings from shell scripts amongst others, covering use of shell special characters or control characters or no characters in both separator and / or parameters, and edge cases, and corner cases and other quibbles like no arguments at all. That doesn't guarantee there is no more bug, but it will be a little harder challenge to find one. BTW, even the currently top voted answers and related suffer from such things like that -e bug ...

Additional examples:

$ join_ws '' a b c
abc
$ join_ws ':' {1,7}{A..C}
1A:1B:1C:7A:7B:7C
$ join_ws -e -e
-e
$ join_ws $'\033[F' $'\n\n\n'  1.  2.  3.  $'\n\n\n\n'
3.
2.
1.
$ join_ws $ 
$

Delete files in subfolder using batch script

Use powershell inside your bat file

PowerShell Remove-Item c:\scripts\* -include *.txt -exclude *test* -force -recurse

You can also exclude from removing some specific folder or file:

PowerShell Remove-Item C:/*  -Exclude WINDOWS,autoexec.bat -force -recurse

Matching a space in regex

It seems to me like using a REGEX in this case would just be overkill. Why not just just strpos to find the space character. Also, there's nothing special about the space character in regular expressions, you should be able to search for it the same as you would search for any other character. That is, unless you disabled pattern whitespace, which would hardly be necessary in this case.

Output Django queryset as JSON

Try this:

class JSONListView(ListView):
    queryset = Users.objects.all()


    def get(self, request, *args, **kwargs):
        data = {}
        data["users"] = get_json_list(queryset)
        return JSONResponse(data)


def get_json_list(query_set):
    list_objects = []
    for obj in query_set:
        dict_obj = {}
        for field in obj._meta.get_fields():
            try:
                if field.many_to_many:
                    dict_obj[field.name] = get_json_list(getattr(obj, field.name).all())
                    continue
                dict_obj[field.name] = getattr(obj, field.name)
            except AttributeError:
                continue
        list_objects.append(dict_obj)
    return list_objects

AttributeError: 'module' object has no attribute 'urlopen'

For python 3, try something like this:

import urllib.request
urllib.request.urlretrieve('http://crcv.ucf.edu/THUMOS14/UCF101/UCF101/v_YoYo_g19_c02.avi', "video_name.avi")

It will download the video to the current working directory

I got help from HERE

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

Pull new updates from original GitHub repository into forked GitHub repository

You have to add the original repository (the one you forked) as a remote.

From the GitHub documentation on forking a repository:

Screenshot of the old GitHub interface with a rectangular lens around the "Fork" button

Once the clone is complete your repo will have a remote named “origin” that points to your fork on GitHub.
Don’t let the name confuse you, this does not point to the original repo you forked from. To help you keep track of that repo we will add another remote named “upstream”:

$ cd PROJECT_NAME
$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
$ git fetch upstream

# then: (like "git pull" which is fetch + merge)
$ git merge upstream/master master

# or, better, replay your local work on top of the fetched branch
# like a "git pull --rebase"
$ git rebase upstream/master

There's also a command-line tool (hub) which can facilitate the operations above.

Here's a visual of how it works:

Flowchart on the result after the commands are executed

See also "Are Git forks actually Git clones?".

Terminating a script in PowerShell

I used this for a reruning of a program. I don't know if it would help, but it is a simple if statement requiring only two different entry's. It worked in powershell for me.

$rerun = Read-Host "Rerun report (y/n)?"

if($rerun -eq "y") { Show-MemoryReport }
if($rerun -eq "n") { Exit }

Don't know if this helps, but i believe this would be along the lines of terminating a program after you have run it. However in this case, every defined input requires a listed and categorized output. You could also have the exit call up a new prompt line and terminate the program that way.

Invoke native date picker from web-app on iOS/Android

In HTML:

  <form id="my_form"><input id="my_field" type="date" /></form>

In JavaScript

_x000D_
_x000D_
   // test and transform if needed_x000D_
    if($('#my_field').attr('type') === 'text'){_x000D_
        $('#my_field').attr('type', 'text').attr('placeholder','aaaa-mm-dd');  _x000D_
    };_x000D_
_x000D_
    // check_x000D_
    if($('#my_form')[0].elements[0].value.search(/(19[0-9][0-9]|20[0-1][0-5])[- \-.](0[1-9]|1[012])[- \-.](0[1-9]|[12][0-9]|3[01])$/i) === 0){_x000D_
        $('#my_field').removeClass('bad');_x000D_
    } else {_x000D_
        $('#my_field').addClass('bad');_x000D_
    };
_x000D_
_x000D_
_x000D_

Convert text to columns in Excel using VBA

If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.

How to get a file or blob from an object URL?

As gengkev alludes to in his comment above, it looks like the best/only way to do this is with an async xhr2 call:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:http%3A//your.blob.url.here', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
  if (this.status == 200) {
    var myBlob = this.response;
    // myBlob is now the blob that the object URL pointed to.
  }
};
xhr.send();

Update (2018): For situations where ES5 can safely be used, Joe has a simpler ES5-based answer below.

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

Consider following code

<ul id="myTask">
  <li>Coding</li>
  <li>Answering</li>
  <li>Getting Paid</li>
</ul>

Now, here goes the difference

// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
  $(this).remove()
});

Now, what if we add a myTask again?

$('#myTask').append('<li>Answer this question on SO</li>');

Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:

$('#myTask').on('click', 'li', function (event) {
  $(event.target).remove()
});

Summary:

The difference between .on() and .click() would be that .click() may not work when the DOM elements associated with the .click() event are added dynamically at a later point while .on() can be used in situations where the DOM elements associated with the .on() call may be generated dynamically at a later point.

Change x axes scale in matplotlib

Try using matplotlib.pyplot.ticklabel_format:

import matplotlib.pyplot as plt
...
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

This applies scientific notation (i.e. a x 10^b) to your x-axis tickmarks

How to set the initial zoom/width for a webview

It is and old question but let me add a detail just in case more people like me arrive here.

The excellent answer posted by Brian is not working for me in Jelly Bean. I have to add also:

browser.setInitialScale(30);

The parameter can be any percentage tha accomplishes that the resized content is smaller than the webview width. Then setUseWideViewPort(true) extends the content width to the maximum of the webview width.

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

I've been struggling with this issue and I've tried numerous "solutions".

However, in the end, the only one that worked and it actually took a few seconds to do it was to: delete and add back new server instance!

Basically, I right clicked on my Tomcat server in Eclipse under Servers and deleted it. Next, I've added a new Tomcat server. Cleaned and redeployed the application and I got rid of this error.

Input from the keyboard in command line application

Since there were no fancy solutions to this problem, I made a tiny class to read and parse the standard input in Swift. You can find it here.

Example

To parse:

+42 st_ring!
-0.987654321 12345678900
.42

You do:

let stdin = StreamScanner.standardInput

if
    let i: Int = stdin.read(),
    let s: String = stdin.read(),
    let d: Double = stdin.read(),
    let i64: Int64 = stdin.read(),
    let f: Float = stdin.read()
{
    print("\(i) \(s) \(d) \(i64) \(f)")  //prints "42 st_ring! -0.987654321 12345678900 0.42"
}

Adjusting HttpWebRequest Connection Timeout in C#

No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.

To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active

public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
    try
    {
        //check the domain first
        if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
        {
            //only now check the url itself
            var request = System.Net.WebRequest.Create(aUrl);
            request.Method = "HEAD";
            request.Timeout = aTimeoutSeconds * 1000;
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
    }
    return false;

}

private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
    try
    {
        using (TcpClient client = new TcpClient())
        {
            var result = client.BeginConnect(aDomain, 80, null, null);

            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

            if (!success)
            {
                return false;
            }

            // we have connected
            client.EndConnect(result);
            return true;
        }
    }
    catch
    {
    }
    return false;
}

jQuery $("#radioButton").change(...) not firing during de-selection

Looks like the change() function is only called when you check a radio button, not when you uncheck it. The solution I used is to bind the change event to every radio button:

$("#r1, #r2, #r3").change(function () {

Or you could give all the radio buttons the same name:

$("input[name=someRadioGroup]:radio").change(function () {

Here's a working jsfiddle example (updated from Chris Porter's comment.)

Per @Ray's comment, you should avoid using names with . in them. Those names work in jQuery 1.7.2 but not in other versions (jsfiddle example.).

Why do we use Base64?

Why not look to the RFC that currently defines Base64?

Base encoding of data is used in many situations to store or transfer
data in environments that, perhaps for legacy reasons, are restricted to US-ASCII [1] data.Base encoding can also be used in new applications that do not have legacy restrictions, simply because it makes it possible to manipulate objects with text editors.

In the past, different applications have had different requirements and thus sometimes implemented base encodings in slightly different ways. Today, protocol specifications sometimes use base encodings in general, and "base64" in particular, without a precise description or reference. Multipurpose Internet Mail Extensions (MIME) [4] is often used as a reference for base64 without considering the consequences for line-wrapping or non-alphabet characters. The purpose of this specification is to establish common alphabet and encoding considerations. This will hopefully reduce ambiguity in other documents, leading to better interoperability.

Base64 was originally devised as a way to allow binary data to be attached to emails as a part of the Multipurpose Internet Mail Extensions.

How to create a folder with name as current date in batch (.bat) files

This should work:

mkdir %date%

If it doesn't, try this:

setlocal enableextensions
mkdir %date%

ORDER BY date and time BEFORE GROUP BY name in mysql

work for me mysql select * from (SELECT number,max(date_added) as datea FROM sms_chat group by number) as sup order by datea desc

Bootstrap 4: Multilevel Dropdown Inside Navigation

The following is MultiLevel dropdown based on bootstrap4. I tried it was according to the bootstrap4 basic dropdown.

_x000D_
_x000D_
.dropdown-submenu{_x000D_
    position: relative;_x000D_
}_x000D_
.dropdown-submenu a::after{_x000D_
    transform: rotate(-90deg);_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 40%;_x000D_
}_x000D_
.dropdown-submenu:hover .dropdown-menu, .dropdown-submenu:focus .dropdown-menu{_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    position: absolute !important;_x000D_
    margin-top: -30px;_x000D_
    left: 100%;_x000D_
}_x000D_
@media (max-width: 992px) {_x000D_
    .dropdown-menu{_x000D_
        width: 50%;_x000D_
    }_x000D_
    .dropdown-menu .dropdown-submenu{_x000D_
        width: auto;_x000D_
    }_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link 1</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown link_x000D_
        </a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
          <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
          <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
          <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" data-toggle="dropdown" href="#">Something else here</a>_x000D_
            <ul class="dropdown-menu">_x000D_
              <a class="dropdown-item" href="#">A</a>_x000D_
              <a class="dropdown-item" href="#">b</a>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

"Cloning" row or column vectors

import numpy as np
x=np.array([1,2,3])
y=np.multiply(np.ones((len(x),len(x))),x).T
print(y)

yields:

[[ 1.  1.  1.]
 [ 2.  2.  2.]
 [ 3.  3.  3.]]

Javascript get object key name

An ES6 update... though both filter and map might need customization.

Object.entries(theObj) returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.

Saves a ton of work on iterating over parts of an object Object.keys(theObj), or Object.values() separately.

_x000D_
_x000D_
const buttons = {_x000D_
    button1: {_x000D_
        text: 'Close',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    },_x000D_
    button2: {_x000D_
        text: 'OK',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    },_x000D_
    button3: {_x000D_
        text: 'Cancel',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
list = Object.entries(buttons)_x000D_
    .filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options_x000D_
    .map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)_x000D_
    _x000D_
console.log(list)
_x000D_
_x000D_
_x000D_

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

A solution which worked in my case is:
  1. Go to the module having Main class.
  2. Right click on pom.xml under this module.
  3. Select "Run Maven" -> "UpdateSnapshots"

How to insert text with single quotation sql server 2005

This worked for me:

  INSERT INTO [TABLE]
  VALUES ('text','''test.com''', 1)

Basically, you take the single quote you want to insert and replace it with two. So if you want to insert a string of text ('text') and add single quotes around it, it would be ('''text'''). Hope this helps.

Django Reverse with arguments '()' and keyword arguments '{}' not found

The solution @miki725 is absolutely correct. Alternatively, if you would like to use the args attribute as opposed to kwargs, then you can simply modify your code as follows:

project_id = 4
reverse('edit_project', args=(project_id,))

An example of this can be found in the documentation. This essentially does the same thing, but the attributes are passed as arguments. Remember that any arguments that are passed need to be assigned a value before being reversed. Just use the correct namespace, which in this case is 'edit_project'.

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .