Programs & Examples On #Early binding

Early binding is a mechanism in which objects are declared to the compiler as being of a specific type.

How to test if a string is JSON or not?

You can try the following one because it also validates number, null, string but the above-marked answer is not working correctly it's just a fix of the above function:

function isJson(str) {
  try {
      const obj = JSON.parse(str);
      if (obj && typeof obj === `object`) {
        return true;
      }
    } catch (err) {
      return false;
    }
   return false;
}

Set up DNS based URL forwarding in Amazon Route53

I was able to use nginx to handle the 301 redirect to the aws signin page.

Go to your nginx conf folder (in my case it's /etc/nginx/sites-available in which I create a symlink to /etc/nginx/sites-enabled for the enabled conf files).

Then add a redirect path

server {
  listen 80;
  server_name aws.example.com;
  return 301 https://myaccount.signin.aws.amazon.com/console;
}

If you are using nginx, you will most likely have additional server blocks (virtualhosts in apache terminology) to handle your zone apex (example.com) or however you have it setup. Make sure that you have one of them set to be your default server.

server {
  listen 80 default_server;
  server_name example.com;
  # rest of config ...
}

In Route 53, add an A record for aws.example.com and set the value to the same IP used for your zone apex.

Set value of textarea in jQuery

Have you tried val?

$("textarea#ExampleMessage").val(result.exampleMessage);

How do I display an alert dialog on Android?

This is a basic sample of how to create an Alert Dialog :

AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Dialog on Android");
dialog.setMessage("Are you sure you want to delete this entry?" );
dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int id) {
        //Action for "Delete".
    }
})
        .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            //Action for "Cancel".
            }
        });

final AlertDialog alert = dialog.create();
alert.show();

enter image description here

How to break out of a loop in Bash?

while true ; do
    ...
    if [ something ]; then
        break
    fi
done

How to SHUTDOWN Tomcat in Ubuntu?

Caveat: I'm running Ubuntu

sudo service --status-all

you can get a list of all running services by typing this command,

If you're running Tomcat as a service it will showes up as ("tomcat"), so run :

sudo service tomcat7 stop

(tomcat7 or 8 or depending to the name that you have in the list of running services )

else and if you are using apache tomcat you will see ("apache2") showing up with the list of services then run :

sudo service apache2 stop

How can I initialise a static Map?

I've done something a bit different. Not the best, but it works for me. Maybe it could be "genericized".

private static final Object[][] ENTRIES =
{
  {new Integer(1), "one"},
  {new Integer(2), "two"},
};
private static final Map myMap = newMap(ENTRIES);

private static Map newMap(Object[][] entries)
{
  Map map = new HashMap();

  for (int x = 0; x < entries.length; x++)
  {
    Object[] entry = entries[x];

    map.put(entry[0], entry[1]);
  }

  return map;
}

Smooth scroll to specific div on click

There are many examples of smooth scrolling using JS libraries like jQuery, Mootools, Prototype, etc.

The following example is on pure JavaScript. If you have no jQuery/Mootools/Prototype on page or you don't want to overload page with heavy JS libraries the example will be of help.

http://jsfiddle.net/rjSfP/

HTML Part:

<div class="first"><button type="button" onclick="smoothScroll(document.getElementById('second'))">Click Me!</button></div>
<div class="second" id="second">Hi</div>

CSS Part:

.first {
    width: 100%;
    height: 1000px;
    background: #ccc;
}

.second {
    width: 100%;
    height: 1000px;
    background: #999;
}

JS Part:

window.smoothScroll = function(target) {
    var scrollContainer = target;
    do { //find scroll container
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop == 0);

    var targetY = 0;
    do { //find the top of target relatively to the container
        if (target == scrollContainer) break;
        targetY += target.offsetTop;
    } while (target = target.offsetParent);

    scroll = function(c, a, b, i) {
        i++; if (i > 30) return;
        c.scrollTop = a + (b - a) / 30 * i;
        setTimeout(function(){ scroll(c, a, b, i); }, 20);
    }
    // start scrolling
    scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
}

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

I'm using Spring STS plugin and a Spring webmvc template project. I had to install the Maven m2e plugin first: http://www.eclipse.org/m2e/

And then clean the project. Under Project -> Clean...

Flash CS4 refuses to let go

What if you compile it using another machine? A fresh installed one would be lovely. I hope your machine is not jealous.

How do you determine the ideal buffer size when using FileInputStream?

As already mentioned in other answers, use BufferedInputStreams.

After that, I guess the buffer size does not really matter. Either the program is I/O bound, and growing buffer size over BIS default, will not make any big impact on performance.

Or the program is CPU bound inside the MessageDigest.update(), and majority of the time is not spent in the application code, so tweaking it will not help.

(Hmm... with multiple cores, threads might help.)

Can an abstract class have a constructor?

package Test1;

public class AbstractClassConstructor {

public AbstractClassConstructor() {

}

    public static void main(String args[]) {
       Demo obj = new Test("Test of code has started");
       obj.test1();
    }

}

abstract class Demo{
    protected final String demoValue;

    public Demo(String testName){
        this.demoValue = testName;
    }

    public abstract boolean test1();
}

class Test extends Demo{

    public Test(String name){
        super(name);
    }

    @Override
    public boolean test1() {
       System.out.println( this.demoValue + " Demo test started");
       return true;
    }

}

How to use (install) dblink in PostgreSQL?

On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:

\i /usr/share/postgresql/8.4/contrib/dblink.sql 

you might need to install the contrib packages: sudo apt-get install postgresql-contrib

Difference between webdriver.get() and webdriver.navigate()

For what it's worth, from my IE9 testing, it looks like there's a difference for URLs that contain a hashbang (a single page app, in my case):

http://www.example.com#page

The driver.get("http://www.example.com#anotherpage") method is handled by the browser as a fragment identifier and JavaScript variables are retained from the previous URL.

While, the navigate().to("http://www.example.com#anotherpage") method is handled by the browser as a address/location/URL bar input and JavaScript variables are not retained from the previous URL.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

I think you should define your origins for client side as bellow:

_x000D_
_x000D_
//server.js_x000D_
const socket = require('socket.io');_x000D_
const app = require('express')();_x000D_
const server = app.listen('port');_x000D_
_x000D_
const io = socket().attach(server);_x000D_
io.origins("your_domain:port www.your_domain:port your_IP:port your_domain:*")_x000D_
_x000D_
io.on('connection', (socket) => {_x000D_
  console.log('connected a new client');_x000D_
});_x000D_
_x000D_
//client.js_x000D_
var socket = io('ws://:port');
_x000D_
_x000D_
_x000D_

javax.servlet.ServletException cannot be resolved to a type in spring web app

I guess this may work, in Eclipse select your project ? then click on project menu bar on top ? goto to properties ? click on Targeted Runtimes ? now you must select a check box next to the server you are using to run current project ? click Apply ? then click OK button. That's it, give a try.

Check if value exists in Postgres array

unnest can be used as well. It expands array to a set of rows and then simply checking a value exists or not is as simple as using IN or NOT IN.

e.g.

  1. id => uuid

  2. exception_list_ids => uuid[]

select * from table where id NOT IN (select unnest(exception_list_ids) from table2)

Select from one table where not in another

So there's loads of posts on the web that show how to do this, I've found 3 ways, same as pointed out by Johan & Sjoerd. I couldn't get any of these queries to work, well obviously they work fine it's my database that's not working correctly and those queries all ran slow.

So I worked out another way that someone else may find useful:

The basic jist of it is to create a temporary table and fill it with all the information, then remove all the rows that ARE in the other table.

So I did these 3 queries, and it ran quickly (in a couple moments).

CREATE TEMPORARY TABLE

`database1`.`newRows`

SELECT

`t1`.`id` AS `columnID`

FROM

`database2`.`table` AS `t1`

.

CREATE INDEX `columnID` ON `database1`.`newRows`(`columnID`)

.

DELETE FROM `database1`.`newRows`

WHERE

EXISTS(
    SELECT `columnID` FROM `database1`.`product_details` WHERE `columnID`=`database1`.`newRows`.`columnID`
)

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

What is @RenderSection in asp.net MVC

Suppose if I have GetAllEmployees.cshtml

<h2>GetAllEmployees</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
         // do something ...
    </thead>
    <tbody>
       // do something ...
    </tbody>
</table>

   //Added my custom scripts in the scripts sections

@section Scripts
    {
    <script src="~/js/customScripts.js"></script>
    }

And another view "GetEmployeeDetails.cshtml" with no scripts

<h2>GetEmployeeByDetails</h2>

@Model.PageTitle
<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
       // do something ... 
    </thead>
    <tbody>
       // do something ...
    </tbody>
</table>

And my layout page "_layout.cshtml"

@RenderSection("Scripts", required: true)

So, when I navigate to GetEmployeeDetails.cshtml. I get the error that there is no section scripts to be rendered in GetEmployeeDetails.cshtml. If I change the flag in @RenderSection() from required : true to ``required : false`. It means render the scripts defined in the @section scripts of the views if present.Else, do nothing. And the refined approach would be in _layout.cshtml

@if (IsSectionDefined("Scripts"))
    {
        @RenderSection("Scripts", required: true)
    }

SQL Server 2008: how do I grant privileges to a username?

Like the following. It will make the user database owner.

EXEC sp_addrolemember N'db_owner', N'USerNAme'

Check to see if python script is running

try this:

#/usr/bin/env python
import os, sys, atexit

try:
    # Set PID file
    def set_pid_file():
        pid = str(os.getpid())
        f = open('myCode.pid', 'w')
        f.write(pid)
        f.close()

    def goodby():
        pid = str('myCode.pid')
        os.remove(pid)

    atexit.register(goodby)
    set_pid_file()
    # Place your code here

except KeyboardInterrupt:
    sys.exit(0)

How can I use nohup to run process as a background process in linux?

  • Use screen: Start screen, start your script, press Ctrl+A, D. Reattach with screen -r.

  • Make a script that takes your "1" as a parameter, run nohup yourscript:

    #!/bin/bash
    (time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
    

Copy folder structure (without files) from one location to another

cd /path/to/directories &&
find . -type d -exec mkdir -p -- /path/to/backup/{} \;

How to count the number of letters in a string without the spaces?

I managed to condense it into two lines of code:

string = input("Enter your string\n")
print(len(string) - string.count(" "))

Return single column from a multi-dimensional array

very simple go for this

$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma 

C++ for each, pulling from vector elements

C++ does not have the for_each loop feature in its syntax. You have to use c++11 or use the template function std::for_each.

struct Function {
    int input;
    Function(int input): input(input) {}
    void operator()(Attack& attack) {
        if(attack->m_num == input) attack->makeDamage();
    }
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);

VBA: Counting rows in a table (list object)

You need to go one level deeper in what you are retrieving.

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("MyTable")
MsgBox tbl.Range.Rows.Count
MsgBox tbl.HeaderRowRange.Rows.Count
MsgBox tbl.DataBodyRange.Rows.Count
Set tbl = Nothing

More information at:

ListObject Interface
ListObject.Range Property
ListObject.DataBodyRange Property
ListObject.HeaderRowRange Property

How to press/click the button using Selenium if the button does not have the Id?

Use xpath selector (here's quick tutorial) instead of id:

#python:
from selenium.webdriver import Firefox

YOUR_PAGE_URL = 'http://mypage.com/'
NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'

browser = Firefox()
browser.get(YOUR_PAGE_URL)

button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()

Or, if you use "vanilla" Selenium, just use same xpath selector instead of button id:

NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'
selenium.click(NEXT_BUTTON_XPATH)

Windows batch file file download from a URL

' Create an HTTP object
myURL = "http://www.google.com"
Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )

' Download the specified URL
objHTTP.Open "GET", myURL, False
objHTTP.Send
intStatus = objHTTP.Status

If intStatus = 200 Then
  WScript.Echo " " & intStatus & " A OK " +myURL
Else
  WScript.Echo "OOPS" +myURL
End If

then

C:\>cscript geturl.vbs
Microsoft (R) Windows Script Host Version 5.7
Copyright (C) Microsoft Corporation. All rights reserved.

200 A OK http://www.google.com

or just double click it to test in windows

Styling the last td in a table with css

For IE, how about using a CSS expression:

<style type="text/css">
table td { 
  h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : '1px solid #000' ) );
}
</style>

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

use getBoundingClientRect if $el is the actual DOM object:

var top = $el.getBoundingClientRect().top;

JSFiddle

Fiddle will show that this will get the same value that jquery's offset top will give you

Edit: as mentioned in comments this does not account for scrolled content, below is the code that jQuery uses

https://github.com/jquery/jquery/blob/master/src/offset.js (5/13/2015)

offset: function( options ) {
    //...

    var docElem, win, rect, doc,
        elem = this[ 0 ];

    if ( !elem ) {
        return;
    }

    rect = elem.getBoundingClientRect();

    // Make sure element is not hidden (display: none) or disconnected
    if ( rect.width || rect.height || elem.getClientRects().length ) {
        doc = elem.ownerDocument;
        win = getWindow( doc );
        docElem = doc.documentElement;

        return {
            top: rect.top + win.pageYOffset - docElem.clientTop,
            left: rect.left + win.pageXOffset - docElem.clientLeft
        };
    }
}

Format number as percent in MS SQL Server

took the challenge to solve this issue. comment number 5 (M.Ali) asked for --"The required answer is 97.36 % (not 0.97 %) .." so for that i'm attaching a photo who compare between post number 3 (sqluser) to my solution. (i'm using the postgre_sql on a mac)

enter image description here

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

Casting a number to a string in TypeScript

Use the "+" symbol to cast a string to a number.

window.location.hash = +page_number;

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

How to return value from an asynchronous callback function?

It makes no sense to return values from a callback. Instead, do the "foo()" work you want to do inside your callback.

Asynchronous callbacks are invoked by the browser or by some framework like the Google geocoding library when events happen. There's no place for returned values to go. A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.

Cannot read property 'length' of null (javascript)

if (capital.touched && capital != undefined && capital.length < 1 ) { 
//capital does exists
}

When to use RDLC over RDL reports?

If we have fewer number of reports which are less complex and consumed by asp.net web pages. It's better to go with rdlc,reason is we can avoid maintaing reports on RS instance. but we have to fetch the data from DB manually and bind it to rdlc.

Cons:designing rdlc in visual studio is little difficult compared to SSrs designer.

Pro:Maintenance is easy. while exporting the report from we page,observed that performance gain compared to server side reports.

How do I horizontally center a span element inside a div

another option would be to give the span display:table; and center it via margin:0 auto;

span {
display:table;
margin:0 auto;
}

How to connect to local instance of SQL Server 2008 Express

I've just solved a problem related to this which may help other people.

Initially when loading up MSSMSE it had the server as PC_NAME\SQLEXPRESS and when I tried to connect it gave me Error: 26 - Error Locating Server/Instance Specified, so I went into SQL Server Configuration Manager to check if my SQL Server Browser and SQL Server services were running and set to automatic, only to find that instead of saying SQL Server (SQLEXPRESS) it says SQL Server(MSSQLSERVER).

I then tried connecting to PC-NAME\MSSQLSERVER and this time got SQL Network Interfaces, error: 25 - Connection string is not valid) (MicrosoftSQL Server, Error: 87) The parameter is incorrect so I googled this error and found that somebody had suggested that instead of using PC-NAME\MSSQLSERVER just use PC-NAME as the Server Name at the server connection interface, and this seems to work.

There's a link here http://learningsqlserver.wordpress.com/2011/01/21/what-version-of-sql-server-do-i-have/ which explains that MSSQLSERVER is the default instance and can be connected to by using just your hostname.

I think this may have arisen because I've had SQL Server 2008 installed at some point in the past.

Function to check if a string is a date

I use this function as a parameter to the PHP filter_var function.

  • It checks for dates in yyyy-mm-dd hh:mm:ss format
  • It rejects dates that match the pattern but still invalid (e.g. Apr 31)

function filter_mydate($s) {
    if (preg_match('@^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$@', $s, $m) == false) {
        return false;
    }
    if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
        return false;
    }
    return $s;
}

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Rename a file in C#

  1. First solution

    Avoid System.IO.File.Move solutions posted here (marked answer included). It fails over networks. However, copy/delete pattern works locally and over networks. Follow one of the move solutions, but replace it with Copy instead. Then use File.Delete to delete the original file.

    You can create a Rename method to simplify it.

  2. Ease of use

    Use the VB assembly in C#. Add reference to Microsoft.VisualBasic

    Then to rename the file:

    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName);

    Both are strings. Note that myfile has the full path. newName does not. For example:

    a = "C:\whatever\a.txt";
    b = "b.txt";
    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b);
    

    The C:\whatever\ folder will now contain b.txt.

How to implement Android Pull-to-Refresh

I think the best library is : https://github.com/chrisbanes/Android-PullToRefresh.

Works with:

ListView
ExpandableListView
GridView
WebView
ScrollView
HorizontalScrollView
ViewPager

How to Access Hive via Python?

similar to @python-starter solution. But, commands package is not avilable on python3.x. So Alternative solution is to use subprocess in python3.x

import subprocess

cmd = "hive -S -e 'SELECT * FROM db_name.table_name LIMIT 1;' "

status, output = subprocess.getstatusoutput(cmd)

if status == 0:
   print(output)
else:
   print("error")

Changing the page title with Jquery

_x000D_
_x000D_
 var isOldTitle = true;_x000D_
        var oldTitle = document.title;_x000D_
        var newTitle = "New Title";_x000D_
        var interval = null;_x000D_
        function changeTitle() {_x000D_
            document.title = isOldTitle ? oldTitle : newTitle;_x000D_
            isOldTitle = !isOldTitle;_x000D_
        }_x000D_
        interval = setInterval(changeTitle, 700);_x000D_
_x000D_
        $(window).focus(function () {_x000D_
            clearInterval(interval);_x000D_
            $("title").text(oldTitle);_x000D_
        });
_x000D_
_x000D_
_x000D_

Use jQuery to change value of a label

.text is correct, the following code works for me:

$('#lb'+(n+1)).text(a[i].attributes[n].name+": "+ a[i].attributes[n].value);

How to refresh a Page using react-route Link

To refresh page you don't need react-router, simple js:

window.location.reload();

To re-render view in React component, you can just fire update with props/state.

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

Include <%@ page isELIgnored="false"%> on top of your jsp page.

Find non-ASCII characters in varchar columns using SQL Server

I've been running this bit of code with success

declare @UnicodeData table (
     data nvarchar(500)
)
insert into 
    @UnicodeData
values 
    (N'Horse?')
    ,(N'Dog')
    ,(N'Cat')

select
    data
from
    @UnicodeData 
where
    data collate LATIN1_GENERAL_BIN != cast(data as varchar(max))

Which works well for known columns.

For extra credit, I wrote this quick script to search all nvarchar columns in a given table for Unicode characters.

declare 
    @sql    varchar(max)    = ''
    ,@table sysname         = 'mytable' -- enter your table here

;with ColumnData as (
    select
        RowId               = row_number() over (order by c.COLUMN_NAME)
        ,c.COLUMN_NAME
        ,ColumnName         = '[' + c.COLUMN_NAME + ']'
        ,TableName          = '[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + ']' 
    from
        INFORMATION_SCHEMA.COLUMNS c
    where
        c.DATA_TYPE         = 'nvarchar'
        and c.TABLE_NAME    = @table
)
select
    @sql = @sql + 'select FieldName = ''' + c.ColumnName + ''',         InvalidCharacter = [' + c.COLUMN_NAME + ']  from ' + c.TableName + ' where ' + c.ColumnName + ' collate LATIN1_GENERAL_BIN != cast(' + c.ColumnName + ' as varchar(max)) '  +  case when c.RowId <> (select max(RowId) from ColumnData) then  ' union all ' else '' end + char(13)
from
    ColumnData c

-- check
-- print @sql
exec (@sql)

I'm not a fan of dynamic SQL but it does have its uses for exploratory queries like this.

How to subtract/add days from/to a date?

The answer probably depends on what format your date is in, but here is an example using the Date class:

dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")

You can even play with different units like weeks.

How to write a multiline command?

After trying almost every key on my keyboard:

C:\Users\Tim>cd ^
Mehr? Desktop

C:\Users\Tim\Desktop>

So it seems to be the ^ key.

Bootstrap Element 100% Width

This is how you can achieve your desired setup with Bootstrap 3:

<div class="container-fluid">
    <div class="row"> <!-- Give this div your desired background color -->
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    ... your content here ...
                </div>
            </div>
        </div>
    </div>
</div>

The container-fluid part makes sure that you can change the background over the full width. The container part makes sure that your content is still wrapped in a fixed width.

This approach works, but personally I don't like all the nesting. However, I haven't found a better solution so far.

How to store decimal values in SQL Server?

DECIMAL(18,0) will allow 0 digits after the decimal point.

Use something like DECIMAL(18,4) instead that should do just fine!

That gives you a total of 18 digits, 4 of which after the decimal point (and 14 before the decimal point).

process.start() arguments

Not really a direct answer, but I'd highly recommend using LINQPad for this kind of "exploratory" C# programming.

I have the following as a saved "query" in LINQPad:

var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c echo Foo && echo Bar";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardOutput.ReadToEnd().Dump();

Feel free to adapt as needed.

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

You can extract all the information from the DbEntityValidationException with the following code (you need to add the namespaces: System.Data.Entity.Validation and System.Diagnostics to your using list):

catch (DbEntityValidationException dbEx)
{
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            Trace.TraceInformation("Property: {0} Error: {1}", 
                                    validationError.PropertyName, 
                                    validationError.ErrorMessage);
        }
    }
}

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go

$ homebrew install mdbtools

Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.

$ ./to_mysql.sh myfile.mdb > myfile.sql

(which btw contains more than 1 table)

Pip freeze vs. pip list

pip list shows ALL installed packages.

pip freeze shows packages YOU installed via pip (or pipenv if using that tool) command in a requirements format.

Remark below that setuptools, pip, wheel are installed when pipenv shell creates my virtual envelope. These packages were NOT installed by me using pip:

test1 % pipenv shell
Creating a virtualenv for this project…
Pipfile: /Users/terrence/Development/Python/Projects/test1/Pipfile
Using /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8 (3.8.1) to create virtualenv…
? Creating virtual environment...
<SNIP>
Installing setuptools, pip, wheel...
done.
? Successfully created virtual environment! 
<SNIP>

Now review & compare the output of the respective commands where I've only installed cool-lib and sampleproject (of which peppercorn is a dependency):

test1 % pip freeze       <== Packages I'VE installed w/ pip

-e git+https://github.com/gdamjan/hello-world-python-package.git@10<snip>71#egg=cool_lib
peppercorn==0.6
sampleproject==1.3.1


test1 % pip list         <== All packages, incl. ones I've NOT installed w/ pip

Package       Version Location                                                                    
------------- ------- --------------------------------------------------------------------------
cool-lib      0.1  /Users/terrence/.local/share/virtualenvs/test1-y2Zgz1D2/src/cool-lib           <== Installed w/ `pip` command
peppercorn    0.6       <== Dependency of "sampleproject"
pip           20.0.2  
sampleproject 1.3.1     <== Installed w/ `pip` command
setuptools    45.1.0  
wheel         0.34.2

Trim characters in Java

EDIT: Amended by answer to replace just the first and last '\' character.

System.err.println("\\joe\\jill\\".replaceAll("^\\\\|\\\\$", ""));

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

After updating to El Capitan, /usr/local has root:wheel rights.

Change the rights back to the user using:

sudo chown -R $(whoami):admin /usr/local

and:

brew doctor && brew update

This helped me to get Homebrew working again.

Skip first entry in for loop in python?

Based on @SvenMarnach 's Answer, but bit simpler and without using deque

>>> def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)

>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
>>> list(skip(range(10), at_start=2, at_end=5))
[2, 3, 4]

Also Note, based on my timeit result, this is marginally faster than the deque solution

>>> iterable=xrange(1000)
>>> stmt1="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)
list(skip(iterable,2,2))
    """
>>> stmt2="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    for x in itertools.islice(it, at_start):
        pass
    queue = collections.deque(itertools.islice(it, at_end))
    for x in it:
        queue.append(x)
        yield queue.popleft()
list(skip(iterable,2,2))
        """
>>> timeit.timeit(stmt = stmt1, setup='from __main__ import iterable, skip, itertools', number = 10000)
2.0313770640908047
>>> timeit.timeit(stmt = stmt2, setup='from __main__ import iterable, skip, itertools, collections', number = 10000)
2.9903135454296716

How to include external Python code to use in other files?

Just write the "include" command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

How to install Jdk in centos

Try the following to see if you have the proper repository installed:

# yum search java | grep 'java-'

This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:

http://dag.wieers.com/rpm/FAQ.php#B

After you've got it installed try yum search again... This time you'll have a bunch of java stuff.

# yum search java | grep 'java-'

This will return the list of the available java packages. You can install one like this:

# yum install java-1.7.0-openjdk.x86_64

How to add a second css class with a conditional value in razor MVC 4

You can add property to your model as follows:

    public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }

and then your view will be simpler and will contain no logic at all:

    <div class="details @Model.DetailsClass"/>

This will work even with many classes and will not render class if it is null:

    <div class="@Model.Class1 @Model.Class2"/>

with 2 not null properties will render:

    <div class="class1 class2"/>

if class1 is null

    <div class=" class2"/>

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

What is the best way to dump entire objects to a log in C#?

You could base something on the ObjectDumper code that ships with the Linq samples.
Have also a look at the answer of this related question to get a sample.

Autonumber value of last inserted row - MS Access / VBA

Both of the examples immediately above didn't work for me. Opening a recordset on the table and adding a record does work to add the record, except:

myLong = CLng(rs!AutoNumberField)

returns Null if put between rs.AddNew and rs.Update. If put after rs.Update, it does return something, but it's always wrong, and always the same incorrect value. Looking at the table directly after adding the new record shows an autonumber field value different than the one returned by the above statement.

myLong = DLookup("AutoNumberField","TableName","SomeCriteria")

will work properly, as long as it's done after rs.Update, and there are any other fields which can uniquely identify the record.

Constructor in an Interface?

A problem that you get when you allow constructors in interfaces comes from the possibility to implement several interfaces at the same time. When a class implements several interfaces that define different constructors, the class would have to implement several constructors, each one satisfying only one interface, but not the others. It will be impossible to construct an object that calls each of these constructors.

Or in code:

interface Named { Named(String name); }
interface HasList { HasList(List list); }

class A implements Named, HasList {

  /** implements Named constructor.
   * This constructor should not be used from outside, 
   * because List parameter is missing
   */
  public A(String name)  { 
    ...
  }

  /** implements HasList constructor.
   * This constructor should not be used from outside, 
   * because String parameter is missing
   */
  public A(List list) {
    ...
  }

  /** This is the constructor that we would actually 
   * need to satisfy both interfaces at the same time
   */ 
  public A(String name, List list) {
    this(name);
    // the next line is illegal; you can only call one other super constructor
    this(list); 
  }
}

MySQL Workbench not displaying query results

I had the same issue. Using MySQL 6.1 Workbench.

After a while (2 mins), it just crashed. Reported bug, saved files and reopened. It works now.

I guess I would suggest if that happens again, to immediately save the open scripts, close MySQL and restart it.

Date Format in Swift

    import UIKit
    // Example iso date time
    let isoDateArray = [
        "2020-03-18T07:32:39.88Z",
        "2020-03-18T07:32:39Z",
        "2020-03-18T07:32:39.8Z",
        "2020-03-18T07:32:39.88Z",
        "2020-03-18T07:32:39.8834Z"
    ]


    let dateFormatterGetWithMs = DateFormatter()
    let dateFormatterGetNoMs = DateFormatter()

// Formater with and without millisecond 
    dateFormatterGetWithMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    dateFormatterGetNoMs.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"

    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "MMM dd,yyyy"

    for dateString in isoDateArray {
        var date: Date? = dateFormatterGetWithMs.date(from: dateString)
        if (date == nil){
            date = dateFormatterGetNoMs.date(from: dateString)
        }
        print("===========>",date!)
    }

How do I sort a two-dimensional (rectangular) array in C#?

Load your two-dimensional string array into an actual DataTable (System.Data.DataTable), and then use the DataTable object's Select() method to generate a sorted array of DataRow objects (or use a DataView for a similar effect).

// assumes stringdata[row, col] is your 2D string array
DataTable dt = new DataTable();
// assumes first row contains column names:
for (int col = 0; col < stringdata.GetLength(1); col++)
{
    dt.Columns.Add(stringdata[0, col]);
}
// load data from string array to data table:
for (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)
{
    DataRow row = dt.NewRow();
    for (int col = 0; col < stringdata.GetLength(1); col++)
    {
        row[col] = stringdata[rowindex, col];
    }
    dt.Rows.Add(row);
}
// sort by third column:
DataRow[] sortedrows = dt.Select("", "3");
// sort by column name, descending:
sortedrows = dt.Select("", "COLUMN3 DESC");

You could also write your own method to sort a two-dimensional array. Both approaches would be useful learning experiences, but the DataTable approach would get you started on learning a better way of handling tables of data in a C# application.

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

Java Compare Two List's object values?

Logic should be something like:

  1. First step: For class MyData implements Comparable interface, override the compareTo method as per the per object requirement.

  2. Second step: When it comes to list comparison (after checking for nulls), 2.1 Check the size of both lists, if equal returns true else return false, continue to object iteration 2.2 If step 2.1 returns true, iterate over elements from both lists and invoke something like,

    listA.get(i).compareTo(listB.get(i))

This will be as per the code mentioned in step-1.

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

You can make the field nullable, if that suits your specific modeling concerns. A null date won't be coerced to a date that isn't within the range of the SQL DateTime type the way a default value would. Another option is to explicitly map to a different type, perhaps with,

.HasColumnType("datetime2")

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

PHP remove commas from numeric strings

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


Do it the other way around:

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

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

The easiest would be:

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

or if you need float:

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

HTML Tags in Javascript Alert() method

No, you can use only some escape sequences - \n for example (maybe only this one).

Junit test case for database insert method with DAO and web service

The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.

To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.

A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.

As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.

RecyclerView vs. ListView

There are many differences between ListView and RecyclerView, but you should be aware of the following in particular:

  • The ViewHolder pattern is entirely optional in ListView, but it’s baked into RecyclerView.
  • ListView only supports vertical scrolling, but RecyclerView isn’t limited to vertically scrolling lists.

Why do I have ORA-00904 even when the column is present?

Its due to mismatch between column name defined in entity and the column name of table (in SQL db )

java.sql.SQLException: ORA-00904: "table_name"."column_name": invalid identifier e.g.java.sql.SQLException: ORA-00904: "STUDENT"."NAME": invalid identifier

issue can be like in Student.java(entity file) 
You have mentioned column name as "NAME" only.
But in STUDENT table ,column name is lets say "NMAE"

Difference between app.use and app.get in express.js

Difference between app.use & app.get:

app.use ? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.

app.get ? It is only for handling GET HTTP requests.

Now, there is a confusion between app.use & app.all. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests. But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.

  1. app.use() ? It takes only one callback.
    app.all() ? It can take multiple callbacks.

  2. app.use() will only see whether url starts with specified path.
    But, app.all() will match the complete path.

For example,

app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject

app.all( "/book" , handler);
// will match /book
// won't match /book/author   
// won't match /book/subject    

app.all( "/book/*" , handler);
// won't match /book        
// will match /book/author
// will match /book/subject
  1. next() call inside the app.use() will call either the next middleware or any route handler, but next() call inside app.all() will invoke the next route handler (app.all(), app.get/post/put... etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

In Visual Studio 2010 the key sequence CTRL+E, S will also toggle display of whitespace characters.

Programmatically add new column to DataGridView

Here's a sample method that adds two extra columns programmatically to the grid view:

    private void AddColumnsProgrammatically()
    {
        // I created these columns at function scope but if you want to access 
        // easily from other parts of your class, just move them to class scope.
        // E.g. Declare them outside of the function...
        var col3 = new DataGridViewTextBoxColumn();
        var col4 = new DataGridViewCheckBoxColumn();

        col3.HeaderText = "Column3";
        col3.Name = "Column3";

        col4.HeaderText = "Column4";
        col4.Name = "Column4";

        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
    }

A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

// Note that this info scattered throughout the designer but can easily collected.

        System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        System.Windows.Forms.DataGridViewCheckBoxColumn Column2;

        this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();

        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.Column1,
        this.Column2});

        this.Column1.HeaderText = "Column1";
        this.Column1.Name = "Column1";

        this.Column2.HeaderText = "Column2";
        this.Column2.Name = "Column2";

Python Library Path

I think you're looking for sys.path

import sys
print (sys.path)

Disable elastic scrolling in Safari

None of the 'overflow' solutions worked for me. I'm coding a parallax effect with JavaScript using jQuery. In Chrome and Safari on OSX the elastic/rubber-band effect was messing up my scroll numbers, since it actually scrolls past the document's height and updates the window variables with out-of-boundary numbers. What I had to do was check if the scrolled amount was larger than the actual document's height, like so:

$(window).scroll(
    function() {
        if ($(window).scrollTop() + $(window).height() > $(document).height()) return;
        updateScroll(); // my own function to do my parallaxing stuff
    }
);

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.

Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.

Which Radio button in the group is checked?

Yet another try - Using event lambda expressions

As form initializes a single event handler can be assigned to all controls of type RadioButton in a group box, and use .tabIndex or .tag property to identify what option is checked when it changes.

This way you can subscribe to any of the events of each radio button in one go

int priceOption = 0;
foreach (RadioButton rbtn in grp_PriceOpt.Controls.OfType<RadioButton>())
{
    rbtn.CheckedChanged += (o, e) =>
    {
        var button = (RadioButton)o;
        if (button.Checked)
        {
            priceOption = button.TabIndex;
        }
    };
}

As events are assigned to radio buttons only, no type checking of sender is implemented.

Also notice as we loop all buttons this could be a perfect moment to assign data properties, change text etc.

Simple function to sort an array of objects

This isn't a JSON question, per se. Its a javascript array question.

Try this:

people.sort(function(a,b){ 
    var x = a.name < b.name? -1:1; 
    return x; 
});

How to determine if a type implements an interface with C# reflection

You have a few choices:

  1. typeof(IMyInterface).IsAssignableFrom(typeof(MyType))

  2. typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))

For a generic interface, it’s a bit different.

typeof(MyType).GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMyInterface<>))

Finding the mode of a list

Simple code that finds the mode of the list without any imports:

nums = #your_list_goes_here
nums.sort()
counts = dict()
for i in nums:
    counts[i] = counts.get(i, 0) + 1
mode = max(counts, key=counts.get)

In case of multiple modes, it should return the minimum node.

Initializing multiple variables to the same value in Java

Works for primitives and immutable classes like String, Wrapper classes Character, Byte.

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

For mutable classes

Reference r1 = Reference r2 = Reference r3 = new Object();`  

Three references + one object are created. All references point to the same object and your program will misbehave.

Capturing multiple line output into a Bash variable

Parsing multiple output

Introduction

So your myscript output 3 lines, could look like:

myscript() { echo $'abc\ndef\nghi'; }

or

myscript() { local i; for i in abc def ghi ;do echo $i; done ;}

Ok this is a function, not a script (no need of path ./), but output is same

myscript
abc
def
ghi

Considering result code

To check for result code, test function will become:

myscript() { local i;for i in abc def ghi ;do echo $i;done;return $((RANDOM%128));}

1. Storing multiple output in one single variable, showing newlines

Your operation is correct:

RESULT=$(myscript)

About result code, you could add:

RCODE=$?

even in same line:

RESULT=$(myscript) RCODE=$?

Then

echo $RESULT 
abc def ghi

echo "$RESULT"
abc
def
ghi

echo ${RESULT@Q}
$'abc\ndef\nghi'

printf "%q\n" "$RESULT"
$'abc\ndef\nghi'

but for showing variable definition, use declare -p:

declare -p RESULT
declare -- RESULT="abc
def
ghi"

2. Parsing multiple output in array, using mapfile

Storing answer into myvar variable:

mapfile -t myvar < <(myscript)
echo ${myvar[2]}
ghi

Showing $myvar:

declare -p myvar
declare -a myvar=([0]="abc" [1]="def" [2]="ghi")

Considering result code

In case you have to check for result code, you could:

RESULT=$(myscript) RCODE=$?
mapfile -t myvar <<<"$RESULT"

3. Parsing multiple output by consecutives read in command group

{ read firstline; read secondline; read thirdline;} < <(myscript)
echo $secondline
def

Showing variables:

declare -p firstline secondline thirdline
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"

I often use:

{ read foo;read foo total use free foo ;} < <(df -k /)

Then

declare -p use free total
declare -- use="843476"
declare -- free="582128"
declare -- total="1515376"

Considering result code

Same prepended step:

RESULT=$(myscript) RCODE=$?
{ read firstline; read secondline; read thirdline;} <<<"$RESULT"

declare -p firstline secondline thirdline RCODE
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"
declare -- RCODE="50"

Getting Current date, time , day in laravel

Here is another way to do this

Use \Carbon\Carbon;

$date = Carbon::now();

echo $date->toRfc850String();

Output will be like this

Saturday, 11-May-19 06:28:04 UTC

Paging with LINQ for objects

I use this extension method:

public static IQueryable<T> Page<T, TResult>(this IQueryable<T> obj, int page, int pageSize, System.Linq.Expressions.Expression<Func<T, TResult>> keySelector, bool asc, out int rowsCount)
{
    rowsCount = obj.Count();
    int innerRows = rowsCount - (page * pageSize);
    if (innerRows < 0)
    {
        innerRows = 0;
    }
    if (asc)
        return obj.OrderByDescending(keySelector).Take(innerRows).OrderBy(keySelector).Take(pageSize).AsQueryable();
    else
        return obj.OrderBy(keySelector).Take(innerRows).OrderByDescending(keySelector).Take(pageSize).AsQueryable();
}

public IEnumerable<Data> GetAll(int RowIndex, int PageSize, string SortExpression)
{
    int totalRows;
    int pageIndex = RowIndex / PageSize;

    List<Data> data= new List<Data>();
    IEnumerable<Data> dataPage;

    bool asc = !SortExpression.Contains("DESC");
    switch (SortExpression.Split(' ')[0])
    {
        case "ColumnName":
            dataPage = DataContext.Data.Page(pageIndex, PageSize, p => p.ColumnName, asc, out totalRows);
            break;
        default:
            dataPage = DataContext.vwClientDetails1s.Page(pageIndex, PageSize, p => p.IdColumn, asc, out totalRows);
            break;
    }

    foreach (var d in dataPage)
    {
        clients.Add(d);
    }

    return data;
}
public int CountAll()
{
    return DataContext.Data.Count();
}

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

import urllib
import urllib.request
from bs4 import BeautifulSoup


with urllib.request.urlopen("http://www.newegg.com/") as url:
    s = url.read()
    print(s)
soup = BeautifulSoup(s, "html.parser")
all_tag_a = soup.find_all("a", limit=10)

for links in all_tag_a:
    #print(links.get('href'))
    print(links)

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

If the problem allows it, try with EXISTS, since it's optimized to end as soon as a result is found (And don't buffer any response), so, if you are just trying to normalize data for a WHERE clause like this

SELECT FROM SOMETHING S WHERE S.ID IN ( SELECT DISTINCT DCR.SOMETHING_ID FROM DIFF_CARDINALITY_RELATIONSHIP DCR ) -- to keep same cardinality

A faster response would be:

SELECT FROM SOMETHING S WHERE EXISTS ( SELECT 1 FROM DIFF_CARDINALITY_RELATIONSHIP DCR WHERE DCR.SOMETHING_ID = S.ID )

This isn't always possible but when available you will see a faster response.

How can I stop a running MySQL query?

If you have mysqladmin available, you may get the list of queries with:

> mysqladmin -uUSERNAME -pPASSWORD pr

+-----+------+-----------------+--------+---------+------+--------------+------------------+
| Id  | User | Host            | db     | Command | Time | State        | Info             |
+-----+------+-----------------+--------+---------+------+--------------+------------------+
| 137 | beet | localhost:53535 | people | Query   | 292  | Sending data | DELETE FROM      |
| 145 | root | localhost:55745 |        | Query   | 0    |              | show processlist |
+-----+------+-----------------+--------+---------+------+--------------+------------------+

Then you may stop the mysql process that is hosting the long running query:

> mysqladmin -uUSERNAME -pPASSWORD kill 137

How to generate graphs and charts from mysql database in php

I use Google Chart Tools https://developers.google.com/chart/ It's well documented and the charts look great. Being javascript, you can feed it json data via ajax.

How to show "Done" button on iPhone number pad

Here's the simplest solution I have come across. I have learnt this from Beginning iOS 5 Development book.

Assuming the number field is called numberField.

  1. In ViewController, add the following method:

    -(IBAction)closeKeyboard:(id)sender;
    
  2. In ViewController.m, add the following code:

    -(IBAction)closeKeyboard:(id)sender
    {
    
         [numberField resignFirstResponder];
    
    }
    
  3. Go back to nib file.

  4. Open Utilities pan.
  5. Open the Identity inspector under Utilities pan.
  6. Click on the View (in nib file) once. Make sure you have not clicked on any of the items in the view. For the sake of clarification, you should see UIView under Class in Identity inspector.
  7. Change the class from UIView to UIControl.
  8. Open Connection Inspector.
  9. Click and drag Touch Down and drop the arrow on File Owner icon. (FYI... File Owner icon is displayed on the left of View and appears as a hollow cube with yellow frame.)
  10. Select the method: closeKeyboard.
  11. Run the program.

Now when you click anywhere on background of View, you should be able to dismiss the keyboard.

Hope this helps you solve your problem. :-)

ToString() function in Go

I prefer something like the following:

type StringRef []byte

func (s StringRef) String() string {
        return string(s[:])
}

…

// rather silly example, but ...
fmt.Printf("foo=%s\n",StringRef("bar"))

How do I make XAML DataGridColumns fill the entire DataGrid?

Another spin on the same theme:

protected void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
    dataGrid.Width = e.NewSize.Width - (e.NewSize.Width * .1);

    foreach (var column in dataGrid.Columns)
    {
       column.Width = dataGrid.Width / dataGrid.Columns.Count;
    }
 }

Unable to connect to SQL Server instance remotely

Disable the firewall and try to connect.

If that works, then enable the firewall and

Windows Defender Firewall -> Advanced Settings -> Inbound Rules(Right Click) -> New Rules -> Port -> Allow Port 1433 (Public and Private) -> Add

Do the same for Outbound Rules.

Then Try again.

Create list of object from another using Java 8 Streams

If you want to iterate over a list and create a new list with "transformed" objects, you should use the map() function of stream + collect(). In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.

public class Test {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("e1", "l1"),
                new Person("e2", "l1"),
                new Person("e3", "l2"),
                new Person("e4", "l2")
        );

        List<Employee> employees = persons.stream()
                .filter(p -> p.getLastName().equals("l1"))
                .map(p -> new Employee(p.getName(), p.getLastName(), 1000))
                .collect(Collectors.toList());

        System.out.println(employees);
    }

}

class Person {

    private String name;
    private String lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }

    // Getter & Setter
}

class Employee extends Person {

    private double salary;

    public Employee(String name, String lastName, double salary) {
        super(name, lastName);
        this.salary = salary;
    }

    // Getter & Setter
}

get all the images from a folder in php

try this

$directory = "mytheme/images/myimages";
$images = glob($directory . "/*.jpg");

foreach($images as $image)
{
  echo $image;
}

jQuery vs. javascript?

Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.

Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.

Javascript is the source, the actual scripts that browser responds to.

How do I set the colour of a label (coloured text) in Java?

For single color foreground color

label.setForeground(Color.RED)

For multiple foreground colors in the same label:

(I would probably put two labels next to each other using a GridLayout or something, but here goes...)

You could use html in your label text as follows:

frame.add(new JLabel("<html>Text color: <font color='red'>red</font></html>"));

which produces:

enter image description here

Generate C# class from XML

I realise that this is a rather old post and you have probably moved on.

But I had the same problem as you so I decided to write my own program.

The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.

It is in no way elegant but it did the job for me.

You can get it here: Please make suggestions if you like it.

SimpleXmlToCode

How to create a WPF Window without a border that can be resized via a grip only?

If you set the AllowsTransparency property on the Window (even without setting any transparency values) the border disappears and you can only resize via the grip.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="640" Height="480" 
    WindowStyle="None"
    AllowsTransparency="True"
    ResizeMode="CanResizeWithGrip">

    <!-- Content -->

</Window>

Result looks like:

Create zip file and ignore directory structure

You can use -j.

-j
--junk-paths
          Store just the name of a saved file (junk the path), and do  not
          store  directory names. By default, zip will store the full path
          (relative to the current directory).

Select something that has more/less than x character

Today I was trying same in db2 and used below, in my case I had spaces at the end of varchar column data

SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(TRIM(EmployeeName))> 4;

How do I create a file at a specific path?

f = open("test.py", "a") Will be created in whatever directory the python file is run from.

I'm not sure about the other error...I don't work in windows.

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

Simple PHP Pagination script

 <?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)

mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    }
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    }
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){

    $id = $row["id"];
    $firstname = $row["firstname"];
    $country = $row["country"];

    $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';

} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
   <div style="margin-left:64px; margin-right:64px;">
     <h2>Total Items: <?php echo $nr; ?></h2>
   </div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html> 

How to use EditText onTextChanged event when I press the number?

In Kotlin Android EditText listener is set using,

   val searchTo : EditText = findViewById(R.id.searchTo)
   searchTo.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable) {

        // you can call or do what you want with your EditText here

        // yourEditText...
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})

How to catch all exceptions in c# using try and catch?

I catch all the exceptions and store it in database, so errors can be corrected easily - the page, place, date etc stored

try
{     
   Cart = DB.BuyOnlineCartMasters.Where(c => c.CmpyID == LoginID && c.Active == true).FirstOrDefault();
}
catch (Exception e)
{
    ErrorReport.StoreError("CartMinifiedPartial-Company", e);  
    -- storing the error for reference
}

Storing

public static void StoreError(string ErrorPage, Exception e)
    {
        try
        {
            eDurar.Models.db_edurarEntities1 DB = new Models.db_edurarEntities1();
            eDurar.Models.ErrorTable Err = new eDurar.Models.ErrorTable();
            Err.ErrorPage = ErrorPage;
            if (e.Message != null)
            {
                Err.ErrorDetails = e.Message;
            }
            if (e.InnerException != null)
            {
                Err.InnerException = e.InnerException.Message.ToString();
            }

            Err.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
            DB.ErrorTables.AddObject(Err);
            DB.SaveChanges();
}

img onclick call to JavaScript function

In response to the good solution from macek. The solution didn't work for me. I have to bind the values of the datas to the export function. This solution works for me:

function exportToForm(a, b, c, d, e) {
  console.log(a, b, c, d, e);
}

var images = document.getElementsByTagName("img");

for (var i=0, len=images.length, img; i<len; i++) {
  var img = images[i];
  var boundExportToForm = exportToForm.bind(undefined, 
          img.getAttribute("data-a"), 
            img.getAttribute("data-b"),
            img.getAttribute("data-c"),
            img.getAttribute("data-d"),
            img.getAttribute("data-e"))

  img.addEventListener("click", boundExportToForm);
  }

How to check for a valid Base64 encoded string

Imho this is not really possible. All posted solutions fails for strings like "test" and so on. If they can be divided through 4, are not null or empty, and if they are a valid base64 character, they will pass all tests. That can be many strings ...

So there is no real solution other than knowing that this is a base 64 encoded string. What I've come up with is this:

if (base64DecodedString.StartsWith("<xml>")
{
    // This was really a base64 encoded string I was expecting. Yippie!
}
else
{
    // This is gibberish.
}

I expect that the decoded string begins with a certain structure, so I check for that.

"Too many characters in character literal error"

Here's an example:

char myChar = '|';
string myString = "||";

Chars are delimited by single quotes, and strings by double quotes.

The good news is C# switch statements work with strings!

switch (mytoken)
{
    case "==":
        //Something here.
        break;
    default:
        //Handle when no token is found.
        break;
}

Moving from one activity to another Activity in Android

button1 in activity2

code written in activity 2

button1.setOnClickListener(new View.OnClickListener() {         
        public void onClick(View v)
        {
            // starting background task to update product               
            Intent fp=new Intent(getApplicationContext(),activity1.class);              
            startActivity(fp);              
        }
    });

This might help

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

Try this

"[A-Za-z0-9_-]+"

Should allow underscores and hyphens

How to import data from one sheet to another

Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.

NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)

Here is a link with the appropriate formulas.

The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))

  • IF(A2="","", means if A2 is blank, return a blank value
  • INDEX(Sheet1!B:B, is saying INDEX B:B where B:B is the data you want to return. IE the name column.
  • Match(A2, is saying to Match A2 which is the ID you want to return the Name for.
  • Sheet1!A:A, is saying you want to match A2 to the ID column in the previous sheet
  • ,0)) is specifying you want an exact value. 0 means return an exact match to A2, -1 means return smallest value greater than or equal to A2, 1 means return the largest value that is less than or equal to A2. Keep in mind -1 and 1 have to be sorted.

More information on the Index/Match formula

Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.

I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.

Good luck! Hope this helps.

Docker: How to delete all local Docker images

Easy and handy commands

To delete all images

docker rmi $(docker images -a)

To delete containers which are in exited state

docker rm $(docker ps -a -f status=exited -q)

To delete containers which are in created state

docker rm $(docker ps -a -f status=created -q)

NOTE: Remove all the containers then remove the images

git visual diff between branches

For those of you on Windows using TortoiseGit, you can get a somewhat visual comparison through this rather obscure feature:

  1. Navigate to the folder you want to compare
  2. Hold down shift and right-click it
  3. Go to TortoiseGit -> Browse Reference
  4. Use ctrl to select two branches to compare
  5. Right-click your selection and click "Compare selected refs"

Source: http://wikgren.fi/compare-diff-branches-in-tortoise-git-or-how-to-preview-changes-before-doing-a-merge/

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

I got the same error but I was trying to run a node application using a Docker container.

I fixed it by adding a .dockerignore file to ignore the node_modules directory to make sure that when the docker image builds, it builds the native packages for the image I wanted (Alpine) instead of copying over the node_modules compiled for my host (Debian).

Add event handler for body.onload by javascript within <body> part

As @epascarello mentioned for W3C standard browsers, you should use:

body.addEventListener("load", init, false);

However, if you want it to work on IE<9 as well you can use:

var prefix = window.addEventListener ? "" : "on";
var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
document.body[eventName](prefix + "load", init, false);

Or if you want it in a single line:

document.body[window.addEventListener ? 'addEventListener' : 'attachEvent'](
    window.addEventListener ? "load" : "onload", init, false);

Note: here I get a straight reference to the body element via the document, saving the need for the first line.

Also, if you're using jQuery, and you want to use the DOM ready event rather than when the body loads, the answer can be even shorter...

$(init);

No module named 'pymysql'

Just a note: for Anaconda install packages command:

  1. python setup.py install

JQuery: Change value of hidden input field

Seems to work

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

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

Vim multiline editing like in sublimetext?

My solution is to use these 2 mappings:

map <leader>n <Esc><Esc>0qq
map <leader>m q:'<,'>-1normal!@q<CR><Down>

How to use them:

  1. Select your lines. If I want to select the next 12 lines I just press V12j
  2. Press <leader>n
  3. Make your changes to the line
  4. Make sure you're in normal mode and then press <leader>m

To make another edit you don't need to make the selection again. Just press <leader>n, make your edit and press <leader>m to apply.


How this works:

  • <Esc><Esc>0qq Exit the visual selection, go to the beginning of the line and start recording a macro.

  • q Stop recording the macro.

  • :'<,'>-1normal!@q<CR> From the start of the visual selection to the line before the end, play the macro on each line.

  • <Down> Go back down to the last line.


You can also just map the same key but for different modes:

vmap <leader>m <Esc><Esc>0qq
nmap <leader>m q:'<,'>-1normal!@q<CR><Down>

Although this messes up your ability to make another edit. You'll have to re-select your lines.

How to include static library in makefile

use

LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

jQuery: outer html()

If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:

var myID = "xxx";

var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";

How can I add additional PHP versions to MAMP

MAMP takes only two highest versions of the PHP in the following folder /Application/MAMP/bin/php

As you can see here highest versions are 7.0.10 and 5.6.25 MAMP php Versions 7.0.10 and 5.6.25

Now 7.0.10 version is removed and as you can see highest two versions are 5.6.25 and 5.5.38 as shown in preferencesphp versions 5.6.25 and 5.5.38

How to call JavaScript function instead of href in HTML

That syntax should work OK, but you can try this alternative.

<a href="javascript:void(0);" onclick="ShowOld(2367,146986,2);">

or

<a href="javascript:ShowOld(2367, 146986, 2);">

UPDATED ANSWER FOR STRING VALUES

If you are passing strings, use single quotes for your function's parameters

<a href="javascript:ShowOld('foo', 146986, 'bar');">

How do I make a simple crawler in PHP?

Why use PHP for this, when you can use wget, e.g.

wget -r -l 1 http://www.example.com

For how to parse the contents, see Best Methods to parse HTML and use the search function for examples. How to parse HTML has been answered multiple times before.

Ignoring directories in Git repositories on Windows

I had some issues creating a file in Windows Explorer with a . at the beginning.

A workaround was to go into the commandshell and create a new file using "edit".

Location of Django logs and errors

Add to your settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

And it will create a file called debug.log in the root of your. https://docs.djangoproject.com/en/1.10/topics/logging/

What does 'foo' really mean?

See: RFC 3092: Etymology of "Foo", D. Eastlake 3rd et al.

Quoting only the relevant definitions from that RFC for brevity:

  1. Used very generally as a sample name for absolutely anything, esp. programs and files (esp. scratch files).

  2. First on the standard list of metasyntactic variables used in syntax examples (bar, baz, qux, quux, corge, grault, garply, waldo, fred, plugh, xyzzy, thud). [JARGON]

How to include file in a bash shell script

Simply put inside your script :

source FILE

Or

. FILE # POSIX compliant

$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.

How to find the most recent file in a directory using .NET, and without looping?

Another approach if you are using Directory.EnumerateFiles and want to read files in latest modified by first.

foreach (string file in Directory.EnumerateFiles(fileDirectory, fileType).OrderByDescending(f => new FileInfo(f).LastWriteTime))

}

How to clone a Date object?

_x000D_
_x000D_
var orig = new Date();
var copy = new Date(+orig);

console.log(orig, copy);
_x000D_
_x000D_
_x000D_

How to count the number of files in a directory using Python

import os

path, dirs, files = next(os.walk("/usr/lib"))
file_count = len(files)

How to find NSDocumentDirectory in Swift?

Apparently, the compiler thinks NSSearchPathDirectory:0 is an array, and of course it expects the type NSSearchPathDirectory instead. Certainly not a helpful error message.

But as to the reasons:

First, you are confusing the argument names and types. Take a look at the function definition:

func NSSearchPathForDirectoriesInDomains(
    directory: NSSearchPathDirectory,
    domainMask: NSSearchPathDomainMask,
    expandTilde: Bool) -> AnyObject[]!
  • directory and domainMask are the names, you are using the types, but you should leave them out for functions anyway. They are used primarily in methods.
  • Also, Swift is strongly typed, so you shouldn't just use 0. Use the enum's value instead.
  • And finally, it returns an array, not just a single path.

So that leaves us with (updated for Swift 2.0):

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

and for Swift 3:

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Sort array by firstname (alphabetically) in Javascript

Basically you can sort arrays with method sort, but if you want to sort objects then you have to pass function to sort method of array, so I will give you an example using your array

user = [{
bio: "<null>",
email: "[email protected]",
firstname: 'Anna',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "<null>",
email: "[email protected]",
firstname: 'Senad',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "<null>",
email: "[email protected]",
firstname: 'Muhamed',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
}];

var ar = user.sort(function(a, b)
{
  var nA = a.firstname.toLowerCase();
  var nB = b.firstname.toLowerCase();

  if(nA < nB)
    return -1;
  else if(nA > nB)
    return 1;
 return 0;
});

Docker remove <none> TAG images

docker rmi $(docker images -a -q)

Stated the following images where in use. I think this command gets rid of unwanted images.

Flutter Countdown Timer

If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!

countDownTimer() async {
 int timerCount;
 for (int x = 5; x > 0; x--) {
   await Future.delayed(Duration(seconds: 1)).then((_) {
     setState(() {
       timerCount -= 1;
    });
  });
 }
}

How to get current time and date in C++?

In C++ 11 you can use std::chrono::system_clock::now()

Example (copied from en.cppreference.com):

#include <iostream>
#include <chrono>
#include <ctime>    

int main()
{
    auto start = std::chrono::system_clock::now();
    // Some computation here
    auto end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}

This should print something like this:

finished computation at Mon Oct  2 00:59:08 2017
elapsed time: 1.88232s

Global variables in AngularJS

Try this, you will not force to inject $rootScope in controller.

app.run(function($rootScope) {
    $rootScope.Currency = 'USD';
});

You can only use it in run block because config block will not provide you to use service of $rootScope.

IIS error, Unable to start debugging on the webserver

In my case it looks like Chrome locking some resources, preventing from debugger to attach. After I closing Chrome, I able to attach again.

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

so if you need want use this code )

import { useRoutes } from "./routes";

import { BrowserRouter as Router } from "react-router-dom";

export const App = () => {

const routes = useRoutes(true);

  return (

    <Router>

      <div className="container">{routes}</div>

    </Router>

  );

};

// ./routes.js 

import { Switch, Route, Redirect } from "react-router-dom";

export const useRoutes = (isAuthenticated) => {
  if (isAuthenticated) {
    return (
      <Switch>
        <Route path="/links" exact>
          <LinksPage />
        </Route>
        <Route path="/create" exact>
          <CreatePage />
        </Route>
        <Route path="/detail/:id">
          <DetailPage />
        </Route>
        <Redirect path="/create" />
      </Switch>
    );
  }
  return (
    <Switch>
      <Route path={"/"} exact>
        <AuthPage />
      </Route>
      <Redirect path={"/"} />
    </Switch>
  );
};

Javascript Array inside Array - how can I call the child array name?

You've made an array of arrays (multidimensional), so options[0] in this case is the size array. you need to reference the first element of the child, which for you is: options[0][0].

If you wanted to loop through all entries you can use the for .. in ... syntax which is described here.

var a = [1,2,4,5,120,12];
for (var val in t) {
    console.log(t[val]);
}

var b = ['S','M','L'];
var both = [a,b];

for (var val in both) {
     for(val2 in both[val]){console.log(both[val][val2])}
}

How to set up default schema name in JPA configuration?

I had to set the value in '' and ""

spring:
   jpa:
     properties:
       hibernate:
          default_schema: '"schema"'

How to do a scatter plot with empty circles in Python?

Basend on the example of Gary Kerr and as proposed here one may create empty circles related to specified values with following code:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.markers import MarkerStyle

x = np.random.randn(60) 
y = np.random.randn(60)
z = np.random.randn(60)

g=plt.scatter(x, y, s=80, c=z)
g.set_facecolor('none')
plt.colorbar()
plt.show()

How to draw vectors (physical 2D/3D vectors) in MATLAB?

            % draw simple vector from pt a to pt b
            % wtr : with respect to
            scale=0;%for drawin  vectors with true scale
            a = [10 20 30];% wrt origine O(0,0,0)
            b = [10 10 20];% wrt origine O(0,0,0)

            starts=a;% a now is the origine of my vector to draw (from a to b) so we made a translation from point O to point  a = to vector a 
            c = b-a;% c is the new coordinates of b wrt origine a 
            ends=c;%
            plot3(a(1),a(2),a(3),'*b')
            hold on
            plot3(b(1),b(2),b(3),'*g')

             quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3),scale);% Use scale = 0 to plot the vectors without the automatic scaling.
            % axis equal
            hold off

CSS Image size, how to fill, but not stretch?

<div class="container">
     <img src="http://i.stack.imgur.com/2OrtT.jpg"/>
</div>

<style>
.container {
       width: 150px;
       height: 100px;
       overflow: hidden;
}
</style>

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

Form.Close() is use to close an instance of a Form with in .NET application it does not kill the entire application. Application.exit() kills your application.

NSUserDefaults - How to tell if a key exists

Swift version to get Bool?

NSUserDefaults.standardUserDefaults().objectForKey(DefaultsIsGiver) as? Bool

Can I change the name of `nohup.out`?

As the file handlers points to i-nodes (which are stored independently from file names) on Linux/Unix systems You can rename the default nohup.out to any other filename any time after starting nohup something&. So also one could do the following:

$ nohup something&
$ mv nohup.out nohup2.out
$ nohup something2&

Now something adds lines to nohup2.out and something2 to nohup.out.

Get clicked item and its position in RecyclerView

After lot of trial and error I found that there is a very easy way to do this that is by creating an interface in adapter class and implementing that in fragment now here comes the twist, I instansiated the view model inside my override function present In the fragment now you can send the data from that function to viemodel and from there anywhere.

I don't know if this method is good coding method but please let me know in comment and if any wants to see the let me know in the comment section I regularly open stackover flow.

Set Background cell color in PHPExcel

$objPHPExcel
->getActiveSheet()
->getStyle('A1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setRGB('colorcode'); //i.e,colorcode=D3D3D3

pySerial write() won't take my string

It turns out that the string needed to be turned into a bytearray and to do this I editted the code to

ser.write("%01#RDD0010000107**\r".encode())

This solved the problem

How to remove default chrome style for select Input?

input:-webkit-autofill { background: #fff !important; }

Intercept a form submit in JavaScript and prevent normal submission

<form onSubmit="return captureForm()"> that should do. Make sure that your captureForm() method returns false.

How to insert element as a first child?

parentNode.insertBefore(newChild, refChild)

Inserts the node newChild as a child of parentNode before the existing child node refChild. (Returns newChild.)

If refChild is null, newChild is added at the end of the list of children. Equivalently, and more readably, use parentNode.appendChild(newChild).

Find files in a folder using Java

You can use a FilenameFilter, like so:

File dir = new File(directory);

File[] matches = dir.listFiles(new FilenameFilter()
{
  public boolean accept(File dir, String name)
  {
     return name.startsWith("temp") && name.endsWith(".txt");
  }
});

How to create a laravel hashed password

The Laravel Hash facade provides secure Bcrypt hashing for storing user passwords.

Basic usage required two things:

First include the Facade in your file

use Illuminate\Support\Facades\Hash;

and use Make Method to generate password.

$hashedPassword = Hash::make($request->newPassword);

and when you want to match the Hashed string you can use the below code:

Hash::check($request->newPasswordAtLogin, $hashedPassword)

You can learn more with the Laravel document link below for Hashing: https://laravel.com/docs/5.5/hashing

How to search if dictionary value contains certain string with Python

You can do it like this:

#Just an example how the dictionary may look like
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
      'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(values, searchFor):
    for k in values:
        for v in values[k]:
            if searchFor in v:
                return k
    return None

#Checking if string 'Mary' exists in dictionary value
print search(myDict, 'Mary') #prints firstName

Get the value of a dropdown in jQuery

This has worked for me!

$('#selected-option option:selected').val()

Hope this helps someone!

MySQL - How to select rows where value is in array?

Use the FIND_IN_SET function:

SELECT t.*
  FROM YOUR_TABLE t
 WHERE FIND_IN_SET(3, t.ids) > 0

SQL Server 2008: How to query all databases sizes?

please find more deatils or download the script from below link https://gallery.technet.microsoft.com/SIZE-OF-ALL-DATABASES-IN-0337f6d5#content

 DECLARE @spacetable table
 (
 database_name varchar(50) ,
 total_size_data int,
 space_util_data int,
 space_data_left int,
 percent_fill_data float,
 total_size_data_log int,
 space_util_log int,
 space_log_left int,
 percent_fill_log char(50),
 [total db size] int,
 [total size used] int,
 [total size left] int
 )
 insert into  @spacetable
 EXECUTE master.sys.sp_MSforeachdb 'USE [?];
 select x.[DATABASE NAME],x.[total size data],x.[space util],x.[total size data]-x.[space util] [space left data],
 x.[percent fill],y.[total size log],y.[space util],
 y.[total size log]-y.[space util] [space left log],y.[percent fill],
 y.[total size log]+x.[total size data] ''total db size''
 ,x.[space util]+y.[space util] ''total size used'',
 (y.[total size log]+x.[total size data])-(y.[space util]+x.[space util]) ''total size left''
  from (select DB_NAME() ''DATABASE NAME'',
 sum(size*8/1024) ''total size data'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
 ,case when sum(size*8/1024)=0 then ''less than 1% used'' else
 substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
 from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=0
 group by type_desc  ) as x ,
 (select 
 sum(size*8/1024) ''total size log'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
 ,case when sum(size*8/1024)=0 then ''less than 1% used'' else
 substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
 from sys.master_files where database_id=DB_ID(DB_NAME())  and  type=1
 group by type_desc  )y'
 select * from @spacetable
 order by database_name

To show only file name without the entire directory path

ls whateveryouwant | xargs -n 1 basename

Does that work for you?

Otherwise you can (cd /the/directory && ls) (yes, parentheses intended)

How to convert a string to lower or upper case in Ruby

The .swapcase method transforms the uppercase latters in a string to lowercase and the lowercase letters to uppercase.

'TESTING'.swapcase #=> testing
'testing'.swapcase #=> TESTING

jQuery removeClass wildcard

Similar to @tremby's answer, here is @Kobi's answer as a plugin that will match either prefixes or suffixes.

  • ex) strips btn-mini and btn-danger but not btn when stripClass("btn-").
  • ex) strips horsebtn and cowbtn but not btn-mini or btn when stripClass('btn', 1)

Code:

$.fn.stripClass = function (partialMatch, endOrBegin) {
    /// <summary>
    /// The way removeClass should have been implemented -- accepts a partialMatch (like "btn-") to search on and remove
    /// </summary>
    /// <param name="partialMatch">the class partial to match against, like "btn-" to match "btn-danger btn-active" but not "btn"</param>
    /// <param name="endOrBegin">omit for beginning match; provide a 'truthy' value to only find classes ending with match</param>
    /// <returns type=""></returns>
    var x = new RegExp((!endOrBegin ? "\\b" : "\\S+") + partialMatch + "\\S*", 'g');

    // https://stackoverflow.com/a/2644364/1037948
    this.attr('class', function (i, c) {
        if (!c) return; // protect against no class
        return c.replace(x, '');
    });
    return this;
};

https://gist.github.com/zaus/6734731

How do I change tab size in Vim?

As a one-liner into vim:

:set tabstop=4 shiftwidth=4

For permanent setup, add these lines to ~/.vimrc:

set tabstop=4
set shiftwidth=4

NOTE: Add set expandtab if you prefer 4-spaces indentation, instead of a tab indentation.

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

Android: How to add R.raw to project?

Try putting a + before R.xyz. That should start showing additional folders, e.g.:

+ R.raw.beep.mp3

SHA1 vs md5 vs SHA256: which to use for a PHP login?

I think using md5 or sha256 or any hash optimized for speed is perfectly fine and am very curious to hear any rebuttle other users might have. Here are my reasons

  1. If you allow users to use weak passwords such as God, love, war, peace then no matter the encryption you will still be allowing the user to type in the password not the hash and these passwords are often used first, thus this is NOT going to have anything to do with encryption.

  2. If your not using SSL or do not have a certificate then attackers listening to the traffic will be able to pull the password and any attempts at encrypting with javascript or the like is client side and easily cracked and overcome. Again this is NOT going to have anything to do with data encryption on server side.

  3. Brute force attacks will take advantage weak passwords and again because you allow the user to enter the data if you do not have the login limitation of 3 or even a little more then the problem will again NOT have anything to do with data encryption.

  4. If your database becomes compromised then most likely everything has been compromised including your hashing techniques no matter how cryptic you've made it. Again this could be a disgruntled employee XSS attack or sql injection or some other attack that has nothing to do with your password encryption.

I do believe you should still encrypt but the only thing I can see the encryption does is prevent people that already have or somehow gained access to the database from just reading out loud the password. If it is someone unauthorized to on the database then you have bigger issues to worry about that's why Sony got took because they thought an encrypted password protected everything including credit card numbers all it does is protect that one field that's it.

The only pure benefit I can see to complex encryptions of passwords in a database is to delay employees or other people that have access to the database from just reading out the passwords. So if it's a small project or something I wouldn't worry to much about security on the server side instead I would worry more about securing anything a client might send to the server such as sql injection, XSS attacks or the plethora of other ways you could be compromised. If someone disagrees I look forward to reading a way that a super encrypted password is a must from the client side.

The reason I wanted to try and make this clear is because too often people believe an encrypted password means they don't have to worry about it being compromised and they quit worrying about securing the website.

What's the difference between the atomic and nonatomic attributes?

Atomicity atomic (default)

Atomic is the default: if you don’t type anything, your property is atomic. An atomic property is guaranteed that if you try to read from it, you will get back a valid value. It does not make any guarantees about what that value might be, but you will get back good data, not just junk memory. What this allows you to do is if you have multiple threads or multiple processes pointing at a single variable, one thread can read and another thread can write. If they hit at the same time, the reader thread is guaranteed to get one of the two values: either before the change or after the change. What atomic does not give you is any sort of guarantee about which of those values you might get. Atomic is really commonly confused with being thread-safe, and that is not correct. You need to guarantee your thread safety other ways. However, atomic will guarantee that if you try to read, you get back some kind of value.

nonatomic

On the flip side, non-atomic, as you can probably guess, just means, “don’t do that atomic stuff.” What you lose is that guarantee that you always get back something. If you try to read in the middle of a write, you could get back garbage data. But, on the other hand, you go a little bit faster. Because atomic properties have to do some magic to guarantee that you will get back a value, they are a bit slower. If it is a property that you are accessing a lot, you may want to drop down to nonatomic to make sure that you are not incurring that speed penalty. Access

courtesy https://academy.realm.io/posts/tmi-objective-c-property-attributes/

Atomicity property attributes (atomic and nonatomic) are not reflected in the corresponding Swift property declaration, but the atomicity guarantees of the Objective-C implementation still hold when the imported property is accessed from Swift.

So — if you define an atomic property in Objective-C it will remain atomic when used by Swift.

courtesy https://medium.com/@YogevSitton/atomic-vs-non-atomic-properties-crash-course-d11c23f4366c

Send JSON via POST in C# and Receive the JSON returned?

I found myself using the HttpClient library to query RESTful APIs as the code is very straightforward and fully async'ed.

(Edit: Adding JSON from question for clarity)

{
  "agent": {                             
    "name": "Agent Name",                
    "version": 1                                                          
  },
  "username": "Username",                                   
  "password": "User Password",
  "token": "xxxxxx"
}

With two classes representing the JSON-Structure you posted that may look like this:

public class Credentials
{
    [JsonProperty("agent")]
    public Agent Agent { get; set; }

    [JsonProperty("username")]
    public string Username { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }

    [JsonProperty("token")]
    public string Token { get; set; }
}

public class Agent
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("version")]
    public int Version { get; set; }
}

you could have a method like this, which would do your POST request:

var payload = new Credentials { 
    Agent = new Agent { 
        Name = "Agent Name",
        Version = 1 
    },
    Username = "Username",
    Password = "User Password",
    Token = "xxxxx"
};

// Serialize our concrete class into a JSON String
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));

// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

using (var httpClient = new HttpClient()) {

    // Do the actual request and await the response
    var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);

    // If the response contains content we want to read it!
    if (httpResponse.Content != null) {
        var responseContent = await httpResponse.Content.ReadAsStringAsync();

        // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
    }
}

How to set viewport meta for iPhone that handles rotation properly?

You don't want to lose the user scaling option if you can help it. I like this JS solution from here.

<script type="text/javascript">
(function(doc) {

    var addEvent = 'addEventListener',
        type = 'gesturestart',
        qsa = 'querySelectorAll',
        scales = [1, 1],
        meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : [];

    function fix() {
        meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1];
        doc.removeEventListener(type, fix, true);
    }

    if ((meta = meta[meta.length - 1]) && addEvent in doc) {
        fix();
        scales = [.25, 1.6];
        doc[addEvent](type, fix, true);
    }

}(document));
</script>

Python: call a function from string name

If it's in a class, you can use getattr:

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

or if it's a function:

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

Skip certain tables with mysqldump

For sake of completeness, here is a script which actually could be a one-liner to get a backup from a database, excluding (ignoring) all the views. The db name is assumed to be employees:

ignore=$(mysql --login-path=root1 INFORMATION_SCHEMA \
    --skip-column-names --batch \
    -e "select 
          group_concat(
            concat('--ignore-table=', table_schema, '.', table_name) SEPARATOR ' '
          ) 
        from tables 
        where table_type = 'VIEW' and table_schema = 'employees'")

mysqldump --login-path=root1 --column-statistics=0 --no-data employees $ignore > "./backups/som_file.sql"   

You can update the logic of the query. In general using group_concat and concat you can generate almost any desired string or shell command.

Core dump file is not generated

Also, check to make sure you have enough disk space on /var/core or wherever your core dumps get written. If the partition is almos full or at 100% disk usage then that would be the problem. My core dumps average a few gigs so you should be sure to have at least 5-10 gig available on the partition.

Clang vs GCC for my Linux Development project

For student level programs, Clang has the benefit that it is, by default, stricter wrt. the C standard. For example, the following K&R version of Hello World is accepted without warning by GCC, but rejected by Clang with some pretty descriptive error messages:

main()
{
    puts("Hello, world!");
}

With GCC, you have to give it -Werror to get it to really make a point about this not being a valid C89 program. Also, you still need to use c99 or gcc -std=c99 to get the C99 language.

C - casting int to char and append char to char

Casting int to char involves losing data and the compiler will probably warn you.

Extracting a particular byte from an int sounds more reasonable and can be done like this:

number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */

Concept behind putting wait(),notify() methods in Object class

Wait and notify method always called on object so whether it may be Thread object or simple object (which does not extends Thread class) Given Example will clear your all the doubts.

I have called wait and notify on class ObjB and that is the Thread class so we can say that wait and notify are called on any object.

public class ThreadA {
    public static void main(String[] args){
        ObjB b = new ObjB();
        Threadc c = new Threadc(b); 
        ThreadD d = new ThreadD(b);
        d.setPriority(5);
        c.setPriority(1);
        d.start();
        c.start();
    }
}

class ObjB {
    int total;
    int count(){
        for(int i=0; i<100 ; i++){
            total += i;
        }
        return total;
    }}


class Threadc extends Thread{
    ObjB b;
    Threadc(ObjB objB){
        b= objB;
    }
    int total;
    @Override
    public void run(){
        System.out.print("Thread C run method");
        synchronized(b){
            total = b.count();
            System.out.print("Thread C notified called ");
            b.notify();
        }
    }
}

class ThreadD extends Thread{
    ObjB b;
    ThreadD(ObjB objB){
        b= objB;
    }
    int total;
    @Override
    public void run(){
        System.out.print("Thread D run method");
        synchronized(b){
            System.out.println("Waiting for b to complete...");
            try {
                b.wait();
                System.out.print("Thread C B value is" + b.total);
                } 
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
    }
}

How can I represent a range in Java?

You will have an if-check no matter how efficient you try to optimize this not-so-intensive computation :) You can subtract the upper bound from the number and if it's positive you know you are out of range. You can perhaps perform some boolean bit-shift logic to figure it out and you can even use Fermat's theorem if you want (kidding :) But the point is "why" do you need to optimize this comparison? What's the purpose?

Exiting from python Command Line

If you stuck in python command line and none of above solutions worked for you, try exit(2)

How to get the date from jQuery UI datepicker

the link to getdate: https://api.jqueryui.com/datepicker/#method-getDate

$("#datepicker").datepicker( 'getDate' );

How do you get an iPhone's device name

Here is class structure of UIDevice

+ (UIDevice *)currentDevice;

@property(nonatomic,readonly,strong) NSString    *name;              // e.g. "My iPhone"
@property(nonatomic,readonly,strong) NSString    *model;             // e.g. @"iPhone", @"iPod touch"
@property(nonatomic,readonly,strong) NSString    *localizedModel;    // localized version of model
@property(nonatomic,readonly,strong) NSString    *systemName;        // e.g. @"iOS"
@property(nonatomic,readonly,strong) NSString    *systemVersion;

How to get duration, as int milli's and float seconds from <chrono>?

Taking a guess at what it is you're asking for. I'm assuming by millisecond frame timer you're looking for something that acts like the following,

double mticks()
{
    struct timeval tv;
    gettimeofday(&tv, 0);
    return (double) tv.tv_usec / 1000 + tv.tv_sec * 1000;
}

but uses std::chrono instead,

double mticks()
{
    typedef std::chrono::high_resolution_clock clock;
    typedef std::chrono::duration<float, std::milli> duration;

    static clock::time_point start = clock::now();
    duration elapsed = clock::now() - start;
    return elapsed.count();
}

Hope this helps.

Figure out size of UILabel based on String in Swift

Swift 5:

If you have UILabel and someway boundingRect isn't working for you (I faced this problem. It always returned 1 line height.) there is an extension to easily calculate label size.

extension UILabel {
    func getSize(constrainedWidth: CGFloat) -> CGSize {
        return systemLayoutSizeFitting(CGSize(width: constrainedWidth, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
    }
}

You can use it like this:

let label = UILabel()
label.text = "My text\nIs\nAwesome"
let labelSize = label.getSize(constrainedWidth:200.0)

Works for me

"No such file or directory" but it exists

I got this error “No such file or directory” but it exists because my file was created in Windows and I tried to run it on Ubuntu and the file contained invalid 15\r where ever a new line was there. I just created a new file truncating unwanted stuff

sleep: invalid time interval ‘15\r’
Try 'sleep --help' for more information.
script.sh: 5: script.sh: /opt/ag/cont: not found
script.sh: 6: script.sh: /opt/ag/cont: not found
root@Ubuntu14:/home/abc12/Desktop# vi script.sh 
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  \r  \n   w   g   e   t       h   t   t   p   :   /

0000400   :   4   1   2   0   /  \r  \n
0000410
root@Ubuntu14:/home/abc12/Desktop# tr -d \\015 < script.sh > script.sh.fixed
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh.fixed 
0000000   #   !   /   u   s   r   /   b   i   n   /   e   n   v       b
0000020   a   s   h  \n   w   g   e   t       h   t   t   p   :   /   /

0000400   /  \n
0000402
root@Ubuntu14:/home/abc12/Desktop# sh -x script.sh.fixed