Programs & Examples On #Concept analysis

How to make a progress bar

I was writing up an answer to a similar question that got deleted, so I'm posting it here in case it's of use to anyone.

The markup can be dropped in anywhere and takes up 50px of vertical real estate even when hidden. (To have it take up no vertical space and instead overlay the top 50px, we can just give the progressContainerDiv absolute positioning (inside any positioned element) and style the display property instead of the visible property.)

The general structure is based on code presented in this Geeks for Geeks article.

_x000D_
_x000D_
const_x000D_
  progressContainerDiv = document.getElementById("progressContainerDiv");_x000D_
  progressShownDiv = document.getElementById("progressShownDiv");_x000D_
let_x000D_
  progress = 0,_x000D_
  percentageIncrease = 10;_x000D_
_x000D_
function animateProgress(){_x000D_
  progressContainerDiv.style.visibility = "visible";_x000D_
  const repeater = setInterval(increaseRepeatedly, 100);_x000D_
  function increaseRepeatedly(){_x000D_
    if(progress >= 100){_x000D_
      clearInterval(repeater);_x000D_
      progressContainerDiv.style.visibility = "hidden";_x000D_
      progressNumberSpan.innerHTML = "";_x000D_
      progress = 1;_x000D_
    }_x000D_
    else{_x000D_
      progress = Math.min(100, progress + percentageIncrease);_x000D_
      progressShownDiv.style.width = progress + "%";_x000D_
      progressNumberSpan.innerHTML = progress + "%";_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
#progressContainerDiv{_x000D_
  visibility: hidden;_x000D_
  height: 40px;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
#progressBackgroundDiv {_x000D_
  width: 50%;_x000D_
  margin-left: 24%;_x000D_
  background-color: #ddd;_x000D_
}_x000D_
  _x000D_
#progressShownDiv {_x000D_
  width: 1%;_x000D_
  height: 20px;_x000D_
  background-color: #4CAF50;_x000D_
}_x000D_
_x000D_
#progressNumberSpan{_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<div id="progressContainerDiv">_x000D_
  <div id="progressBackgroundDiv">_x000D_
    <div id="progressShownDiv"></div>_x000D_
  </div>_x000D_
  <div id="progressNumberContainerDiv">_x000D_
    <span id="progressNumberSpan"></span>_x000D_
  </div>_x000D_
</div>_x000D_
<button type="button" onclick="animateProgress()">Go</button>_x000D_
<div id="display"></div>
_x000D_
_x000D_
_x000D_

How do I create a URL shortener?

public class UrlShortener {
    private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int    BASE     = ALPHABET.length();

    public static String encode(int num) {
        StringBuilder sb = new StringBuilder();
        while ( num > 0 ) {
            sb.append( ALPHABET.charAt( num % BASE ) );
            num /= BASE;
        }
        return sb.reverse().toString();   
    }

    public static int decode(String str) {
        int num = 0;
        for ( int i = 0; i < str.length(); i++ )
            num = num * BASE + ALPHABET.indexOf(str.charAt(i));
        return num;
    }   
}

Aligning rotated xticklabels with their respective xticks

If you dont want to modify the xtick labels, you can just use:

plt.xticks(rotation=45)

Converting HTML string into DOM elements?

Here is a little code that is useful.

var uiHelper = function () {

var htmls = {};

var getHTML = function (url) {
                /// <summary>Returns HTML in a string format</summary>
                /// <param name="url" type="string">The url to the file with the HTML</param>

    if (!htmls[url])
    {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, false);
    xmlhttp.send();
    htmls[url] = xmlhttp.responseText;
     };
     return htmls[url];
    };

        return {
            getHTML: getHTML
        };
}();

--Convert the HTML string into a DOM Element

String.prototype.toDomElement = function () {

        var wrapper = document.createElement('div');
        wrapper.innerHTML = this;
        var df= document.createDocumentFragment();
        return df.addChilds(wrapper.children);
};

--prototype helper

HTMLElement.prototype.addChilds = function (newChilds) {
        /// <summary>Add an array of child elements</summary>
        /// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
        /// <returns type="this" />
        for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
        return this;
};

--Usage

 thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();

Create multiple threads and wait all of them to complete

If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.

Example:

List<Thread> threads = new List<Thread>();


// Start threads
for(int i = 0; i<10; i++)
{
    int tmp = i; // Copy value for closure
    Thread t = new Thread(() => Console.WriteLine(tmp));
    t.Start;
    threads.Add(t);
}

// Await threads
foreach(Thread thread in threads)
{
    thread.Join();
}

How to loop through Excel files and load them into a database using SSIS package?

Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx

Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\

In the folder path F:\Temp\, create an Excel 2007 spreadsheet file named States_1.xlsx with two worksheets.

Sheet 1 of States_1.xlsx contained the following data

States_1_Sheet_1

Sheet 2 of States_1.xlsx contained the following data

States_1_Sheet_2

In the folder path F:\Temp\, create another Excel 2007 spreadsheet file named States_2.xlsx with two worksheets.

Sheet 1 of States_2.xlsx contained the following data

States_2_Sheet_1

Sheet 2 of States_2.xlsx contained the following data

States_2_Sheet_2

Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [State] [nvarchar](255) NULL,
    [Country] [nvarchar](255) NULL,
    [FilePath] [nvarchar](255) NULL,
    [SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

The table is currently empty.

Empty table

Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$ to avoid design time error.

Variables

In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.

Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx

ExcelSchema 1

Click on the All section on the left side and set the property Extended Properties to Excel 12.0 to denote the version of Excel. Here in this case 12.0 denotes Excel 2007. Click on the Test Connection to make sure that the connection succeeds.

ExcelSchema 2

Create an Excel connection manager named Excel as shown below.

Excel

Create an OLE DB Connection SQL Server named SQLServer. So, we should have three connections on the package as shown below.

Connections

We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.

On the connection ExcelSchema, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

ExcelSchema ServerName

Similarly on the connection Excel, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

Excel ServerName

On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container named Loop files will loop through the files. The second Foreach Loop container will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL

Control Flow

Configure the first Foreach loop container named Loop files as shown below:

Foreach Loop 1 Collection

Foreach Loop 1 Variable Mappings

Configure the first Foreach loop container named Loop sheets as shown below:

Foreach Loop 2 Collection

Foreach Loop 2 Variable Mappings

Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:

Data Flow Task

Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.

Excel Source Connection Manager

Excel Source Columns

Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.

Derived column

Configure the OLE DB destination to insert the data into the SQL table.

OLE DB Destination Connection Manager

OLE DB Destination Columns

Below screenshot shows successful execution of the package.

Execution successful

Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.

SQL table

Hope that helps.

How to add Active Directory user group as login in SQL Server

Go to the SQL Server Management Studio, navigate to Security, go to Logins and right click it. A Menu will come up with a button saying "New Login". There you will be able to add users and/or groups from Active Directory to your SQL Server "permissions". Hope this helps

What is the difference between id and class in CSS, and when should I use them?

If there is something to add to the previous good answers, it is to explain why ids must be unique per page. This is important to understand for a beginner because applying the same id to multiple elements within the same page will not trigger any error and rather has the same effects as a class.

So from an HTML/CSS perspective, the uniqueness of id per page does not make a sens. But from the JavaScript perspective, it is important to have one id per element per page because getElementById() identifies, as its name suggests, elements by their ids.

So even if you are a pure HTML/CSS developer, you must respect the uniqueness aspect of ids per page for two good reasons:

  1. Clarity: whenever you see an id you are sure it does not exist elsewhere within the same page
  2. Scalability: Even if you are developing only in HTML/CSS, you need to take in consideration the day where you or an other developer will move on to maintain and add functionality to your website in JavaScript.

Retrieving the last record in each group - MySQL

If performance is really your concern you can introduce a new column on the table called IsLastInGroup of type BIT.

Set it to true on the columns which are last and maintain it with every row insert/update/delete. Writes will be slower, but you'll benefit on reads. It depends on your use case and I recommend it only if you're read-focused.

So your query will look like:

SELECT * FROM Messages WHERE IsLastInGroup = 1

Add spaces between the characters of a string in Java?

I am creating a java method for this purpose with dynamic character

public String insertSpace(String myString,int indexno,char myChar){
    myString=myString.substring(0, indexno)+ myChar+myString.substring(indexno);
    System.out.println(myString);
    return myString;
}

How Can I Truncate A String In jQuery?

Instead of using jQuery, use css property text-overflow:ellipsis. It will automatically truncate the string.

.truncated { display:inline-block; 
             max-width:100px; 
             overflow:hidden; 
             text-overflow:ellipsis; 
             white-space:nowrap; 
           }

How to declare strings in C

Strings in C are represented as arrays of characters.

char *p = "String";

You are declaring a pointer that points to a string stored some where in your program (modifying this string is undefined behavior) according to the C programming language 2 ed.

char p2[] = "String";

You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.

char p3[5] = "String";

You are declaring an array of size 5 and initializing it with "String". This is an error be cause "String" don't fit in 5 elements.

char p3[7] = "String"; is the correct declaration ('\0' is the terminating character in c strings).

http://c-faq.com/~scs/cclass/notes/sx8.html

Checking if a number is a prime number in Python

This is the most efficient way to see if a number is prime, if you only have a few query. If you ask a lot of numbers if they are prime try Sieve of Eratosthenes.

import math

def is_prime(n):
    if n == 2:
        return True
    if n % 2 == 0 or n <= 1:
        return False

    sqr = int(math.sqrt(n)) + 1

    for divisor in range(3, sqr, 2):
        if n % divisor == 0:
            return False
    return True

Float a div right, without impacting on design

Try setting its position to absolute. That takes it out of the flow of the document.

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

What is __declspec and when do I need to use it?

It is mostly used for importing symbols from / exporting symbols to a shared library (DLL). Both Visual C++ and GCC compilers support __declspec(dllimport) and __declspec(dllexport). Other uses (some Microsoft-only) are documented in the MSDN.

QED symbol in latex

enter image description here

\documentclass{scrartcl}
\usepackage{amssymb}
\begin{document}
$\backslash$blacksquare: $\blacksquare$

$\backslash$square: $\square$
\end{document}

You can easily find such symbols with http://write-math.com

When you want to align it to the right, add \hfill.

I use:

\renewcommand{\qed}{\hfill\blacksquare}
\newcommand{\qedwhite}{\hfill \ensuremath{\Box}}

HTTPS using Jersey Client

If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.

SSLContext sslContext = null;
try {
  sslContext = SSLContext.getInstance("SSL");
  // Create a new X509TrustManager
  sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
  throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
  .sslContext(sslContext).build();
return client;

private TrustManager[] getTrustManager() {
  return new TrustManager[] {
    new X509TrustManager() {
      @Override
      public X509Certificate[] getAcceptedIssuers() {
        return null;
      }
      @Override
      public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
      @Override
      public void checkClientTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
    }
  };
}

"NoClassDefFoundError: Could not initialize class" error

I had this:

 class Util {
  static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}

you can probably see the problem, the env var might return null instead of string. So just to test my theory, I changed it to:

 class Util {
  static boolean isNeverAsync = false;
}

and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.

Git: "Corrupt loose object"

I had this same problem in my bare remote git repo. After much troubleshooting, I figured out one of my coworkers had made a commit in which some files in .git/objects had permissions of 440 (r--r-----) instead of 444 (r--r--r--). After asking the coworker to change the permissions with "chmod 444 -R objects" inside the bare git repo, the problem was fixed.

Declare global variables in Visual Studio 2010 and VB.NET

None of these answers seem to be changing anything for me.

I am converting an old Excel program to VB 2008. Of course, there are many Excel specific things to change, but something that is causing a headache seems to be this whole "Public" issue.

I have about 40 arrays all being referenced by about 20 modules. The arrays form the foundation of the entire project and are addressed by just about every procedure.

In Excel, I simply had to declare them all as Public. Worked great. No problem. But in VB2008, I'm finding it quite an issue. It is absurd to think that I have to go through thousands of lines of code merely to tell each reference where the Public has been declared. But even willing to do that, none of the schemes being proposed seems to help at all.

It appears that "Public" merely means "Public within this one module". Adding "Shared" seems to do nothing to change that. Adding the module name or anything else doesn't seem to change that. Each module insists that I declare all arrays (and about 100 other fundamental variables) within each module (a seemingly backward advance). And the "Imports" bit doesn't seem to know what I am talking about either, "cannot be found".

I have to sympathize with the questioner. Something seems terribly amiss with all of this.

scroll image with continuous scrolling using marquee tag

Try this:

<marquee behavior="" Height="200px"  direction="up" scroll onmouseover="this.setAttribute('scrollamount', 0, 0);this.stop();" onmouseout="this.setAttribute('scrollamount', 3, 0);this.start();" scrollamount="3" valign="center">

    <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
    </marquee>

Check string length in PHP

[0]=> string(141) means that $message is an array, not string, and $message[0] is a string with 141 characters in length.

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

jQuery-UI datepicker default date

$("#birthdate" ).datepicker("setDate", new Date(1985,01,01))

How to leave space in HTML

“Insensitive to space” is an oversimplification. A more accurate description is that consecutive whitespace characters (spaces, tabs, newlines) are equivalent to a single space, in normal content.

You make empty spaces between words using space characters: “hello world”. I you want more space, you should consider what you are doing, since in normal text content, that does not make sense. For spacing elements, use CSS margin properties.

To get useful example codes, you need to describe a specific problem, like markup and a description of desired rendering.

Update multiple rows with different values in a single SQL query

Use a comma ","

eg: 
UPDATE my_table SET rowOneValue = rowOneValue + 1, rowTwoValue  = rowTwoValue + ( (rowTwoValue / (rowTwoValue) ) + ?) * (v + 1) WHERE value = ?

jQuery Ajax Request inside Ajax Request

Call second ajax from 'complete'

Here is the example

   var dt='';
   $.ajax({
    type: "post",
    url: "ajax/example.php",
    data: 'page='+btn_page,
    success: function(data){
        dt=data;
        /*Do something*/
    },
    complete:function(){
        $.ajax({
           var a=dt; // This line shows error.
           type: "post",
           url: "example.php",
           data: 'page='+a,
           success: function(data){
              /*do some thing in second function*/
           },
       });
    }
});

How to update Xcode from command line

I am now running OS Big Sur. xcode-select --install, and sudo xcode-select --reset did not resolve my issue, neither did the recommended subsequent softwareupdate --install -a command. For good measure, I tried the recommended download from Apple Downloads, but the Command Line Tools downloads available there are not compatible with my OS.

I upvoted the fix that resolved for me, sudo xcode-select --switch /Library/Developer/CommandLineTools/ and added this post for environment context.

Check for internet connection with Swift

With the help of below code you can check for internet Connection for both cellular network as well as for wifi. language - Swift 3.0

import UIKit
import Foundation
import SystemConfiguration

class NetworkConnection: UIViewController {

  class func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
      $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
        SCNetworkReachabilityCreateWithAddress(nil, $0)
      }
    }) else {
      return false
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {
      return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
  }

  class func checkConnection(sender:UIViewController){
    if NetworkConnection.isConnectedToNetwork() == true {
      print("Connected to the internet")
      //  Do something
    } else {
      print("No internet connection")
      let alertController = UIAlertController(title: "No Internet Available", message: "", preferredStyle: UIAlertControllerStyle.alert)
      let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default){(result:UIAlertAction) -> Void in
        return
      }
      alertController.addAction(okAction)
      sender.present(alertController, animated: true, completion: nil)
      //  Do something
    }
  }

}

How to add a linked source folder in Android Studio?

You can add a source folder to the build script and then sync. Look for sourceSets in the documentation here: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Basic-Project

I haven't found a good way of adding test source folders. I have manually added the source to the .iml file. Of course this means it will go away everytime the build script is synched.

How to configure encoding in Maven?

In my case I was using the maven-dependency-plugin so in order to resolve the issue I had to add the following property:

  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

See Apache Maven Resources Plugin / Specifying a character encoding scheme

A long bigger than Long.MAX_VALUE

Firstly, the below method doesn't compile as it is missing the return type and it should be Long.MAX_VALUE in place of Long.Max_value.

public static boolean isBiggerThanMaxLong(long value) {
      return value > Long.Max_value;
}

The above method can never return true as you are comparing a long value with Long.MAX_VALUE , see the method signature you can pass only long there.Any long can be as big as the Long.MAX_VALUE, it can't be bigger than that.

You can try something like this with BigInteger class :

public static boolean isBiggerThanMaxLong(BigInteger l){
    return l.compareTo(BigInteger.valueOf(Long.MAX_VALUE))==1?true:false;
}

The below code will return true :

BigInteger big3 = BigInteger.valueOf(Long.MAX_VALUE).
                  add(BigInteger.valueOf(Long.MAX_VALUE));
System.out.println(isBiggerThanMaxLong(big3)); // prints true

Comparing object properties in c#

I think it would be best to follow the pattern for Override Object#Equals()
For a better description: Read Bill Wagner's Effective C# - Item 9 I think

public override Equals(object obOther)
{
  if (null == obOther)
    return false;
  if (object.ReferenceEquals(this, obOther)
    return true;
  if (this.GetType() != obOther.GetType())
    return false;
  # private method to compare members.
  return CompareMembers(this, obOther as ThisClass);
}
  • Also in methods that check for equality, you should return either true or false. either they are equal or they are not.. instead of throwing an exception, return false.
  • I'd consider overriding Object#Equals.
  • Even though you must have considered this, using Reflection to compare properties is supposedly slow (I dont have numbers to back this up). This is the default behavior for valueType#Equals in C# and it is recommended that you override Equals for value types and do a member wise compare for performance. (Earlier I speed-read this as you have a collection of custom Property objects... my bad.)

Update-Dec 2011:

  • Of course, if the type already has a production Equals() then you need another approach.
  • If you're using this to compare immutable data structures exclusively for test purposes, you shouldn't add an Equals to production classes (Someone might hose the tests by chainging the Equals implementation or you may prevent creation of a production-required Equals implementation).

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

_x000D_
_x000D_
$("h3").text("context")
_x000D_
_x000D_
_x000D_

Just use method "text()".

The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

http://api.jquery.com/text/

Center the content inside a column in Bootstrap 4

2020 : Similar Issue

If your content is a set of buttons that you want to center on a page, then wrap them in a row and use justify-content-center.

Sample code below:

<div class="row justify-content-center">

    <button>Action A</button>
    <button>Action B</button>
    <button>Action C</button> 

</div>

How to load Spring Application Context

I am using in the way and it is working for me.

public static void main(String[] args) {
    new CarpoolDBAppTest();

}

public CarpoolDBAppTest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    Student stud = (Student) context.getBean("yourBeanId");
}

Here Student is my classm you will get the class matching yourBeanId.

Now work on that object with whatever operation you want to do.

Nested jQuery.each() - continue/break

Confirm in API documentation http://api.jquery.com/jQuery.each/ say:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

and this is my example http://jsfiddle.net/r6jqP/

(function($){
    $('#go').on('click',function(){
        var i=0,
            all=0;
        $('li').each(function(){
             all++;
             if($('#mytext').val()=='continue')return true;
             i++;
             if($('#mytext').val()==$(this).html()){
                 return false;
             }
        });
        alert('Iterazione : '+i+' to '+all);
    });
}(jQuery));

Programmatically open new pages on Tabs

Those of you trying to use the following:

window.open('page.html', '_newtab');

should really look at the window.open method.

All you are doing is telling the browser to open a new window NAMED "_newtab" and load page.html into it. Every new page you load will load into that window. However, if a user has their browser set to open new pages in new tabs instead of new windows, it will open a tab. Regardless, it's using the same name for the window or tab.

If you want different pages to open in different windows or tabs you will have to change the NAME of the new window/tab to something different such as:

window.open('page2.html', '_newtab2');

Of course the name for the new window/tab could be any name like page1, page2, page3, etc. instead of _newtab2.

How to undo the last commit in git

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

Artificially create a connection timeout error

  • 10.0.0.0
  • 10.255.255.255
  • 172.16.0.0
  • 172.31.255.255
  • 192.168.0.0
  • 192.168.255.255

All these are non-routable.

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

How to pre-populate the sms body text via an html link

For using Android you use below code

<a href="sms:+32665?body=reg fb1>Send SMS</a>

For iOS you can use below code

<a href="sms:+32665&body=reg fb1>Send SMS</a>

below code working for both iOs and Android

<a href="sms:+32665?&body=reg fb1>Send SMS</a>

Insert current date into a date column using T-SQL?

UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID

If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE() as the default value for that column, and don't allow NULLs

find without recursion

I believe you are looking for -maxdepth 1.

Count the number of occurrences of a string in a VARCHAR field?

This is the mysql function using the space technique (tested with mysql 5.0 + 5.5): CREATE FUNCTION count_str( haystack TEXT, needle VARCHAR(32)) RETURNS INTEGER DETERMINISTIC RETURN LENGTH(haystack) - LENGTH( REPLACE ( haystack, needle, space(char_length(needle)-1)) );

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

php pdo: get the columns name of a table

Just Put your Database name,username,password (Where i marked ?) and table name.& Yuuppiii!.... you get all data from your main database (with column name)

<?php 

function qry($q){

    global $qry;
    try {   
    $host = "?";
    $dbname = "?";
    $username = "?";
    $password = "?";
    $dbcon = new PDO("mysql:host=$host; 
    dbname=$dbname","$username","$password");
}
catch (Exception $e) {

    echo "ERROR ".$e->getMEssage();

}

    $qry = $dbcon->query($q);
    $qry->setFetchMode(PDO:: FETCH_OBJ);

    return $qry;

}


echo "<table>";

/*Get Colums Names in table row */
$columns = array();

$qry1= qry("SHOW COLUMNS FROM Your_table_name");

while (@$column = $qry1->fetch()->Field) {
    echo "<td>".$column."</td>";
    $columns[] = $column;

}

echo "<tr>";

/* Fetch all data into a html table * /

$qry2 = qry("SELECT * FROM Your_table_name");

while ( $details = $qry2->fetch()) {

    echo "<tr>";
    foreach ($columns as $c_name) {
    echo "<td>".$details->$c_name."</td>";

}

}

echo "</table>";

?>

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

If your FK column table should contain that FK value as a primary key Value then data will be inserted.

How to check if a line is blank using regex

Actually in multiline mode a more correct answer is this:

/((\r\n|\n|\r)$)|(^(\r\n|\n|\r))|^\s*$/gm

The accepted answer: ^\s*$ does not match a scenario when the last line is blank (in multiline mode).

'foo' was not declared in this scope c++

In C++ you are supposed to declare functions before you can use them. In your code integrate is not declared before the point of the first call to integrate. The same applies to sum. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.

Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable, getSkewNormal, integrate etc. have no business being in header file.

Also SkewNormalEvalutatable e(); declaration in C++ declares a function e, not an object e as you seem to assume. The simple SkewNormalEvalutatable e; will declare an object initialized by default constructor.

Also, you receive the last parameter of integrate (and of sum) by value as an object of Evaluatable type. That means that attempting to pass SkewNormalEvalutatable as last argument of integrate will result in SkewNormalEvalutatable getting sliced to Evaluatable. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.

Failed binder transaction when putting an bitmap dynamically in a widget

The right approach is to use setImageViewUri() (slower) or the setImageViewBitmap() and recreating RemoteViews every time you update the notification.

C# How to change font of a label

I noticed there was not an actual full code answer, so as i come across this, i have created a function, that does change the font, which can be easily modified. I have tested this in

- XP SP3 and Win 10 Pro 64

private void SetFont(Form f, string name, int size, FontStyle style)
{
    Font replacementFont = new Font(name, size, style);
    f.Font = replacementFont;
}

Hint: replace Form to either Label, RichTextBox, TextBox, or any other relative control that uses fonts to change the font on them. By using the above function thus making it completely dynamic.

    /// To call the function do this.
    /// e.g in the form load event etc.

public Form1()
{
      InitializeComponent();
      SetFont(this, "Arial", 8, FontStyle.Bold);  
      // This sets the whole form and 
      // everything below it.
      // Shaun Cassidy.
}

You can also, if you want a full libary so you dont have to code all the back end bits, you can download my dll from Github.

Github DLL

/// and then import the namespace
using Droitech.TextFont;

/// Then call it using:
TextFontClass fClass = new TextFontClass();
fClass.SetFont(this, "Arial", 8, FontStyle.Bold);

Simple.

git ignore vim temporary files

I found this will have git ignore temporary files created by vim:

[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
*.un~
Session.vim
.netrwhist
*~

It can also be viewed here.

Is there a "null coalescing" operator in JavaScript?

beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript. 1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:

var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts

in such case, the type of your variable is actually Object. test it.

window.alert(typeof myEmptyValue); // prints Object
  1. Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:

    if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
    // alerts
    

if such case, the type of your variable is 'undefined'.

notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).

Image style height and width not taken in outlook mails

make the image the exact size needed in the email. Windows MSO has a hard time resizing images in different scenarios.

in the case of using a 1px by 1px transparent png or gif as a spacer, defining the dimensions via width, height, or style attributes will work as expected in the majority of clients, but not windows MSO (of course).

example use case - you are using a background image and need to position a with a link inside over some part of the background image. Using a 1px by 1px spacer gif/png will only expand so wide (about 30px). You need size the spacer to the exact dimensions.

C# nullable string error

You are making it complicated. string is already nullable. You don't need to make it more nullable. Take out the ? on the property type.

How to strip a specific word from a string?

Easiest way would be to simply replace it with an empty string.

s = s.replace('papa', '')

#ifdef in C#

#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif

Make sure you have the checkbox to define DEBUG checked in your build properties.

Convert Float to Int in Swift

Like this:

var float:Float = 2.2 // 2.2
var integer:Int = Int(float) // 2 .. will always round down.  3.9 will be 3
var anotherFloat: Float = Float(integer) // 2.0

Copy filtered data to another sheet using VBA

Best way of doing it

Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.

  Sub selectVisibleRange()

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
    Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")

    DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
    DuplicateRecords.Cells(1, 1).PasteSpecial


    End Sub

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

C# removing items from listbox

You can't modify the references in an enumerator whilst you enumerate over it; you must keep track of the ones to remove then remove them.

This is an example of the work around:

List<string> listbox = new List<string>();
List<object> toRemove = new List<object>();

foreach (string item in listbox)
{
    string removelistitem = "OBJECT";
    if (item.Contains(removelistitem))
    {
        toRemove.Add(item);
    }
}

foreach (string item in toRemove)
{
    listbox.Remove(item);
}

But if you're using c#3.5, you could say something like this.

listbox.Items = listbox.Items.Select(n => !n.Contains("OBJECT"));

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

This might also be the displayed error message if you try to run 32-bit gcc binaries on a 64-bit OS and missing 32-bit glibc. According to this readme: "For 64 bit system, 32 bit libc and libncurses are required to run the tools.". In this case there is no problem with the path and cc1 is actually found, but reported as missing as no 32 bit glibc.

MS Access VBA: Sending an email through Outlook

Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.

Public Function SendEmail2()

Dim varName As Variant          
Dim varCC As Variant            
Dim varSubject As Variant      
Dim varBody As Variant          

varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','

varSubject = "Hello"
'Email subject

varBody = "Let's get ice cream this week"

'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File

End Function

How to create batch file in Windows using "start" with a path and command with spaces

Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:

start "" "c:\path with spaces\app.exe" param1 "param with spaces"

You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

Better to declare it styleable, so you can change its property from xml:

private boolean swipeable;

public MyViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyViewPager);
    try {
        swipeable = a.getBoolean(R.styleable.MyViewPager_swipeable, true);
    } finally {
        a.recycle();
    }
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    return swipeable ? super.onInterceptTouchEvent(event) : false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return swipeable ? super.onTouchEvent(event) : false;
}

And in your values/attr.xml:

<declare-styleable name="MyViewPager">
  <attr name="swipeable" format="boolean" />
</declare-styleable>

so that you can use it in you layout xml:

<mypackage.MyViewPager
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:swipeable="false" />

Of course, you can still have a get/set property.

How get total sum from input box values using Javascript?

I need to sum the span elements so I edited Akhil Sekharan's answer below.

var arr = document.querySelectorAll('span[id^="score"]');
var total=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].innerHTML))
            total+= parseInt(arr[i].innerHTML);
    }
console.log(total)

You can change the elements with other elements link will guide you with editing.

https://www.w3.org/TR/css3-selectors/#attribute-substrings

How to include a class in PHP

Your code should be something like

require_once('class.twitter.php');

$t = new twitter;
$t->username = 'user';
$t->password = 'password';

$data = $t->publicTimeline();

Checking if a folder exists (and creating folders) in Qt, C++

If you need an empty folder you can loop until you get an empty folder

    QString folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    while(QDir(folder).exists())
    {
         folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    }
    QDir().mkdir(folder);

This case you will get a folder name with a number .

Moving from one activity to another Activity in Android

Below code is working fine with Android 4.3:

Intent i = new Intent(this,MainActivity2.class);
startActivity(i);

Hibernate vs JPA vs JDO - pros and cons of each?

I made a sample WebApp in May 2012 that uses JDO 3.0 & DataNucleus 3.0 - take a look how clean it is: https://github.com/TorbenVesterager/BadAssWebApp

Okay maybe it's a little bit too clean, because I use the POJOs both for the database and the JSON client, but it's fun :)

PS: Contains a few SuppressWarnings annotations (developed in IntelliJ 11)

Convert a String In C++ To Upper Case

Using Boost.Text, which will work for Unicode text

boost::text::text t = "Hello World";
boost::text::text uppered;
boost::text::to_title(t, std::inserter(uppered, uppered.end()));
std::string newstr = uppered.extract();

How to spawn a process and capture its STDOUT in .NET?

I just tried this very thing and the following worked for me:

StringBuilder outputBuilder;
ProcessStartInfo processStartInfo;
Process process;

outputBuilder = new StringBuilder();

processStartInfo = new ProcessStartInfo();
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.Arguments = "<insert command line arguments here>";
processStartInfo.FileName = "<insert tool path here>";

process = new Process();
process.StartInfo = processStartInfo;
// enable raising events because Process does not raise events by default
process.EnableRaisingEvents = true;
// attach the event handler for OutputDataReceived before starting the process
process.OutputDataReceived += new DataReceivedEventHandler
(
    delegate(object sender, DataReceivedEventArgs e)
    {
        // append the new data to the data already read-in
        outputBuilder.Append(e.Data);
    }
);
// start the process
// then begin asynchronously reading the output
// then wait for the process to exit
// then cancel asynchronously reading the output
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.CancelOutputRead();

// use the output
string output = outputBuilder.ToString();

right click context menu for datagridview

While this question is old, the answers aren't proper. Context menus have their own events on DataGridView. There is an event for row context menu and cell context menu.

The reason for which these answers aren't proper is they do not account for different operation schemes. Accessibility options, remote connections, or Metro/Mono/Web/WPF porting might not work and keyboard shortcuts will down right fail (Shift+F10 or Context Menu key).

Cell selection on right mouse click has to be handled manually. Showing the context menu does not need to be handled as this is handled by the UI.

This completely mimics the approach used by Microsoft Excel. If a cell is part of a selected range, the cell selection doesn't change and neither does CurrentCell. If it isn't, the old range is cleared and the cell is selected and becomes CurrentCell.

If you are unclear on this, CurrentCell is where the keyboard has focus when you press the arrow keys. Selected is whether it is part of SelectedCells. The context menu will show on right click as handled by the UI.

private void dgvAccount_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex != -1 && e.RowIndex != -1 && e.Button == System.Windows.Forms.MouseButtons.Right)
    {
        DataGridViewCell c = (sender as DataGridView)[e.ColumnIndex, e.RowIndex];
        if (!c.Selected)
        {
            c.DataGridView.ClearSelection();
            c.DataGridView.CurrentCell = c;
            c.Selected = true;
        }
    }
}

Keyboard shortcuts do not show the context menu by default, so we have to add them in.

private void dgvAccount_KeyDown(object sender, KeyEventArgs e)
{
    if ((e.KeyCode == Keys.F10 && e.Shift) || e.KeyCode == Keys.Apps)
    {
        e.SuppressKeyPress = true;
        DataGridViewCell currentCell = (sender as DataGridView).CurrentCell;
        if (currentCell != null)
        {
            ContextMenuStrip cms = currentCell.ContextMenuStrip;
            if (cms != null)
            {
                Rectangle r = currentCell.DataGridView.GetCellDisplayRectangle(currentCell.ColumnIndex, currentCell.RowIndex, false);
                Point p = new Point(r.X + r.Width, r.Y + r.Height);
                cms.Show(currentCell.DataGridView, p);
            }
        }
    }
}

I've reworked this code to work statically, so you can copy and paste them into any event.

The key is to use CellContextMenuStripNeeded since this will give you the context menu.

Here's an example using CellContextMenuStripNeeded where you can specify which context menu to show if you want to have different ones per row.

In this context MultiSelect is True and SelectionMode is FullRowSelect. This is just for the example and not a limitation.

private void dgvAccount_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    if (e.RowIndex == -1 || e.ColumnIndex == -1)
        return;
    bool isPayment = true;
    bool isCharge = true;
    foreach (DataGridViewRow row in dgv.SelectedRows)
    {
        if ((string)row.Cells["P/C"].Value == "C")
            isPayment = false;
        else if ((string)row.Cells["P/C"].Value == "P")
            isCharge = false;
    }
    if (isPayment)
        e.ContextMenuStrip = cmsAccountPayment;
    else if (isCharge)
        e.ContextMenuStrip = cmsAccountCharge;
}

private void cmsAccountPayment_Opening(object sender, CancelEventArgs e)
{
    int itemCount = dgvAccount.SelectedRows.Count;
    string voidPaymentText = "&Void Payment"; // to be localized
    if (itemCount > 1)
        voidPaymentText = "&Void Payments"; // to be localized
    if (tsmiVoidPayment.Text != voidPaymentText) // avoid possible flicker
        tsmiVoidPayment.Text = voidPaymentText;
}

private void cmsAccountCharge_Opening(object sender, CancelEventArgs e)
{
    int itemCount = dgvAccount.SelectedRows.Count;
    string deleteChargeText = "&Delete Charge"; //to be localized
    if (itemCount > 1)
        deleteChargeText = "&Delete Charge"; //to be localized
    if (tsmiDeleteCharge.Text != deleteChargeText) // avoid possible flicker
        tsmiDeleteCharge.Text = deleteChargeText;
}

private void tsmiVoidPayment_Click(object sender, EventArgs e)
{
    int paymentCount = dgvAccount.SelectedRows.Count;
    if (paymentCount == 0)
        return;

    bool voidPayments = false;
    string confirmText = "Are you sure you would like to void this payment?"; // to be localized
    if (paymentCount > 1)
        confirmText = "Are you sure you would like to void these payments?"; // to be localized
    voidPayments = (MessageBox.Show(
                    confirmText,
                    "Confirm", // to be localized
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2
                   ) == DialogResult.Yes);
    if (voidPayments)
    {
        // SQLTransaction Start
        foreach (DataGridViewRow row in dgvAccount.SelectedRows)
        {
            //do Work    
        }
    }
}

private void tsmiDeleteCharge_Click(object sender, EventArgs e)
{
    int chargeCount = dgvAccount.SelectedRows.Count;
    if (chargeCount == 0)
        return;

    bool deleteCharges = false;
    string confirmText = "Are you sure you would like to delete this charge?"; // to be localized
    if (chargeCount > 1)
        confirmText = "Are you sure you would like to delete these charges?"; // to be localized
    deleteCharges = (MessageBox.Show(
                    confirmText,
                    "Confirm", // to be localized
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2
                   ) == DialogResult.Yes);
    if (deleteCharges)
    {
        // SQLTransaction Start
        foreach (DataGridViewRow row in dgvAccount.SelectedRows)
        {
            //do Work    
        }
    }
}

python: Change the scripts working directory to the script's own directory

This will change your current working directory to so that opening relative paths will work:

import os
os.chdir("/home/udi/foo")

However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do this, you can use the os.path functions:

import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

This takes the filename of your script, converts it to an absolute path, then extracts the directory of that path, then changes into that directory.

Disable scrolling in webview?

My dirty, but easy-to-implement and well working solution:

Simply put the webview inside a scrollview. Make the webview to be far too bigger than the possible content (in one or both dimensions, depending on the requirements). ..and set up the scrollview's scrollbar(s) as you wish.

Example to disable the horizontal scrollbar on a webview:

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="vertical"
>
    <WebView
        android:id="@+id/mywebview"
        android:layout_width="1000dip"
        android:layout_height="fill_parent"
    />
</ScrollView>

I hope this helps ;)

MySQL: #126 - Incorrect key file for table

mysql> set global sql_slave_skip_counter=1; start slave; show slave status\G

Then got error exists :

 Error 'Table './openx/f_scraper_banner_details' is marked as crashed and should be repaired' on query. Default database: 'openx'. Query: 'INSERT INTO f_scraper_banner_details(job_details_id, ad_id, client_id, zone_id, affiliateid, comments, pct_to_report, publisher_currency, sanity_check_enabled, status, error_code, report_date) VALUES (10274859, 321264, 0, 31926, 0, '', -1, 'USD', 1, 'FAILURE', 'INACTIVE_BANNER', '2016-06-28 04:00:00')'
 mysql> repair table f_scraper_banner_details;

This worked for me

@Nullable annotation usage

It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.

It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

Android Color Picker

try this open source projects that might help you

https://github.com/QuadFlask/colorpicker

Windows ignores JAVA_HOME: how to set JDK as default?

I have this issue too. I am running 1.6 but want to build the code I'm working on with 1.5. I've changed the JAVA_HOME and PATH (both user and system) to no avail.

The answer is that the installer for 1.6 dropped java.exe, javaw.exe, and javaws.exe into my Windows\System32 folder (Windows 7).

I solved it by renaming those files to java_wrong.exe, javaw_wrong.exe, and javaws_wrong.exe. Only after doing that does it pick up the correct version of java as defined in JAVA_HOME and PATH. I renamed the files thusly because that deleted them in an easily reversible manner.

Hope this helps!

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

How to make a section of an image a clickable link

If you don't want to make the button a separate image, you can use the <area> tag. This is done by using html similar to this:

<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">

<map name="mapname">
    <area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>

Note 1: The coords=" " attribute must be formatted in this way: coords="x1,y1,x2,y2" where:

x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate

Note 2: The usemap="#mapname" attribute must include the #.

EDIT:

I looked at your code and added in the <map> and <area> tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.

<div class="flexslider">
    <ul class="slides" runat="server" id="Ul">                             
        <li class="flex-active-slide" style="background: url(&quot;images/slider-bg-1.jpg&quot;) no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
            <div class="container">
                <div class="sixteen columns contain"></div>   
                <img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
                <map name="imgmap">
                    <area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
                </map>
                <!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
            </div>
        </li>
    </ul>
</div>
<!-- <ul class="flex-direction-nav">
    <li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
    <li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->

Notes:

  1. The coord="48,341,294,275" is in reference to your screenshot you posted.
  2. The src="./test.png" is the location and name of the screenshot you posted on my computer.
  3. The href="http://www.example.com/" is an example link.

psql: could not connect to server: No such file or directory (Mac OS X)

I was facing a similar issue here I solved this issue as below.

Actually the postgres process is dead, to see the status of postgres run the following command

sudo /etc/init.d/postgres status

It will says the process is dead`just start the process

sudo /etc/init.d/postgres start

How to redirect the output of an application in background to /dev/null

You use:

yourcommand  > /dev/null 2>&1

If it should run in the Background add an &

yourcommand > /dev/null 2>&1 &

>/dev/null 2>&1 means redirect stdout to /dev/null AND stderr to the place where stdout points at that time

If you want stderr to occur on console and only stdout going to /dev/null you can use:

yourcommand 2>&1 > /dev/null

In this case stderr is redirected to stdout (e.g. your console) and afterwards the original stdout is redirected to /dev/null

If the program should not terminate you can use:

nohup yourcommand &

Without any parameter all output lands in nohup.out

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

Get value from hidden field using jQuery

If you don't want to assign identifier to the hidden field; you can use name or class with selector like:

$('input[name=hiddenfieldname]').val();

or with assigned class:

$('input.hiddenfieldclass').val();

How to make use of ng-if , ng-else in angularJS

You can also try ternary operator. Something like this

{{data.id === 5 ? "it's true" : "it's false"}}

Change your html code little bit and try this hope so it will be work for you.

SQL Server Management Studio alternatives to browse/edit tables and run queries

Oracle has a free program called SQL Developer which will work with Microsoft SQL Server as well as Oracle & MySQL. When accessing SQL Server, however, Oracle SQL Developer is only intended to enable an easy migration to Oracle, so your SQL Server database is essentially read-only.

Big-oh vs big-theta

Because my keyboard has an O key.
It does not have a T or an O key.

I suspect most people are similarly lazy and use O when they mean T because it's easier to type.

Clone an image in cv2 python

If you use cv2, correct method is to use .copy() method in Numpy. It will create a copy of the array you need. Otherwise it will produce only a view of that object.

eg:

In [1]: import numpy as np

In [2]: x = np.arange(10*10).reshape((10,10))

In [4]: y = x[3:7,3:7].copy()

In [6]: y[2,2] = 1000

In [8]: 1000 in x
Out[8]: False     # see, 1000 in y doesn't change values in x, parent array.

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

Yes strings must be quoted and in some cases like in applescript, quotes must be escaped

do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

How to create multiple output paths in Webpack config

I wrote a plugin that can hopefully do what you want, you can specify known or unknown entry points (using glob) and specify exact outputs or dynamically generate them using the entry file path and name. https://www.npmjs.com/package/webpack-entry-plus

Android Studio shortcuts like Eclipse

Using Eclipse key mapping inside Android Studio is the better choice. It will easily adapt to existing key structure. But all the new persons are using new shortcut key structures in Android Studio has. So we will learn and follow Android Studio itself contain shortcuts will help easily interact the team mates.

If you use Android Studio in Max OS X mean to follow the below link. It works for me. https://stackoverflow.com/a/30891985/2219406

COUNT / GROUP BY with active record?

I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries: select, group_by, etc. You'll add a plus select: SQL_CALC_FOUND_ROWS user_id. After this query run a query: SELECT FOUND_ROWS(). This will return the desired number.

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

Same problem with VBA Macros using MSCOMCTL.OCX. Problem still unresolved with solutions like "reg/unreg mscomctl.ocx" Used the Info above of Rumi. Edited my *.dot file, search for #2.0#0, change it to #2.1#0 --> it worked

Concatenate multiple files but include filename as section headers

If you like colors, try this:

for i in *; do echo; echo $'\e[33;1m'$i$'\e[0m'; cat $i; done | less -R

or:

tail -n +1 * | grep -e $ -e '==.*'

or: (with package 'multitail' installed)

multitail *

ORA-01652 Unable to extend temp segment by in tablespace

You don't need to create a new datafile; you can extend your existing tablespace data files.

Execute the following to determine the filename for the existing tablespace:

  SELECT * FROM DBA_DATA_FILES;

Then extend the size of the datafile as follows (replace the filename with the one from the previous query):

  ALTER DATABASE DATAFILE 'D:\ORACLEXE\ORADATA\XE\SYSTEM.DBF' RESIZE 2048M; 

How to remove all white spaces in java

String a="string with                multi spaces ";
//or this 
String b= a.replaceAll("\\s+"," ");

String c= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");

//it work fine with any spaces

*don't forget space in sting b

How do you add an image?

The other option to try is a straightforward

<img width="100" height="100" src="/root/Image/image.jpeg" class="CalloutRightPhoto"/>

i.e. without {} but instead giving the direct image path

JavaScript error: "is not a function"

I also hit this error. In my case the root cause was async related (during a codebase refactor): An asynchronous function that builds the object to which the "not a function" function belongs was not awaited, and the subsequent attempt to invoke the function throws the error, example below:

const car = carFactory.getCar();
car.drive() //throws TypeError: drive is not a function

The fix was:

const car = await carFactory.getCar();
car.drive()

Posting this incase it helps anyone else facing this error.

Number input type that takes only integers?

Set the step attribute to 1:

<input type="number" step="1" />

This seems a bit buggy in Chrome right now so it might not be the best solution at the moment.

A better solution is to use the pattern attribute, that uses a regular expression to match the input:

<input type="text" pattern="\d*" />

\d is the regular expression for a number, * means that it accepts more than one of them. Here is the demo: http://jsfiddle.net/b8NrE/1/

Get selected row item in DataGrid WPF

if I select the second row -

 Dim jason As DataRowView


    jason = dg1.SelectedItem

    noteText.Text = jason.Item(0).ToString()

noteText will be 646. This is VB, but you get it.

Custom height Bootstrap's navbar

I believe you are using Bootstrap 3. If so, please try this code, here is the bootply

<header>
    <div class="navbar navbar-static-top navbar-default">
        <div class="navbar-header">
            <a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="glyphicon glyphicon-th-list"></span>
            </a>
        </div>
        <div class="container" style="background:yellow;">
            <a href="/">
                <img src="img/logo.png" class="logo img-responsive">
            </a>

            <nav class="navbar-collapse collapse pull-right" style="line-height:150px; height:150px;">
                <ul class="nav navbar-nav" style="display:inline-block;">
                    <li><a href="">Portfolio</a></li>
                    <li><a href="">Blog</a></li>
                    <li><a href="">Contact</a></li>
                </ul>
            </nav>
        </div>
    </div>
</header>

php: how to get associative array key from numeric index?

If it is the first element, i.e. $array[0], you can try:

echo key($array);

If it is the second element, i.e. $array[1], you can try:

next($array);
echo key($array);

I think this method is should be used when required element is the first, second or at most third element of the array. For other cases, loops should be used otherwise code readability decreases.

Delete topic in Kafka 0.8.1.1

There is actually a solution without touching those bin/kafka-*.sh: If you have installed kafdrop, then simply do:

url -XPOST http://your-kafdrop-domain/topic/THE-TOPIC-YOU-WANT-TO-DELETE/delete

Iterate two Lists or Arrays with one ForEach statement in C#

This is known as a Zip operation and will be supported in .NET 4.

With that, you would be able to write something like:

var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { "one", "two", "three", "four" };

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
    Console.WriteLine(nw.Number + nw.Word);
}

As an alternative to the anonymous type with the named fields, you can also save on braces by using a Tuple and its static Tuple.Create helper:

foreach (var nw in numbers.Zip(words, Tuple.Create)) 
{
    Console.WriteLine(nw.Item1 + nw.Item2);
}

Generate unique random numbers between 1 and 100

function getUniqueRandomNos() {
    var indexedArrayOfRandomNo = [];
    for (var i = 0; i < 100; i++) {
        var randNo = Math.random();
        indexedArrayOfRandomNo.push([i, randNo]);
    }
    indexedArrayOfRandomNo.sort(function (arr1, arr2) {
        return arr1[1] - arr2[1]
    });
    var uniqueRandNoArray = [];
    for (i = 0; i < 8; i++) {
        uniqueRandNoArray.push(indexedArrayOfRandomNo[i][0]);
    }
    return uniqueRandNoArray;
}

I think this method is different from methods given in most of the answers, so I thought I might add an answer here (though the question was asked 4 years ago).

We generate 100 random numbers, and tag each of them with numbers from 1 to 100. Then we sort these tagged random numbers, and the tags get shuffled randomly. Alternatively, as needed in this question, one could do away with just finding top 8 of the tagged random numbers. Finding top 8 items is cheaper than sorting the whole array.

One must note here, that the sorting algorithm influences this algorithm. If the sorting algorithm used is stable, there is slight bias in favor of smaller numbers. Ideally, we would want the sorting algorithm to be unstable and not even biased towards stability (or instability) to produce an answer with perfectly uniform probability distribution.

Bootstrap 3: pull-right for col-lg only

Just use bootstrap's responsive utility classes!

The best solution for that task is to use the following code:

<div class="row">
    <div class="col-lg-6 col-md-6">elements 1</div>
    <div class="col-lg-6 col-md-6 text-right">
        <div class="visible-lg-inline-block visible-md-block visible-sm-block visible-xs-block">
            elements 2
        </div>
    </div>
</div>

Element will be aligned to the right only on lg screens - on the rest the display attribute will be set to block as it is by default for div element. This approach is using text-right class on the parent element instead of pull-right.

Alternative solution:

The biggest disadvantage is that the html code inside needs to be repeated twice.

<div class="row">
    <div class="col-lg-6 col-md-6">elements 1</div>
    <div class="col-lg-6 col-md-6">
         <div class="pull-right visible-lg">
            elements 2
         </div>
         <div class="hidden-lg">
            elements 2
         </div>
    </div>
</div>

'readline/readline.h' file not found

You reference a Linux distribution, so you need to install the readline development libraries

On Debian based platforms, like Ubuntu, you can run:

sudo apt-get install libreadline-dev 

and that should install the correct headers in the correct places,.

If you use a platform with yum, like SUSE, then the command should be:

yum install readline-devel

How to pass parameters to ThreadStart method in Thread?

According to your question...

How to pass parameters to Thread.ThreadStart() method in C#?

...and the error you encountered, you would have to correct your code from

Thread thread = new Thread(new ThreadStart(download(filename));

to

Thread thread = new Thread(new ThreadStart(download));
thread.Start(filename);



However, the question is more complex as it seems at first.

The Thread class currently (4.7.2) provides several constructors and a Start method with overloads.

These relevant constructors for this question are:

public Thread(ThreadStart start);

and

public Thread(ParameterizedThreadStart start);

which either take a ThreadStart delegate or a ParameterizedThreadStart delegate.

The corresponding delegates look like this:

public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(object obj);

So as can be seen, the correct constructor to use seems to be the one taking a ParameterizedThreadStart delegate so that some method conform to the specified signature of the delegate can be started by the thread.

A simple example for instanciating the Thread class would be

Thread thread = new Thread(new ParameterizedThreadStart(Work));

or just

Thread thread = new Thread(Work);

The signature of the corresponding method (called Work in this example) looks like this:

private void Work(object data)
{
   ...
}

What is left is to start the thread. This is done by using either

public void Start();

or

public void Start(object parameter);

While Start() would start the thread and pass null as data to the method, Start(...) can be used to pass anything into the Work method of the thread.

There is however one big problem with this approach: Everything passed into the Work method is cast into an object. That means within the Work method it has to be cast to the original type again like in the following example:

public static void Main(string[] args)
{
    Thread thread = new Thread(Work);

    thread.Start("I've got some text");
    Console.ReadLine();
}

private static void Work(object data)
{
    string message = (string)data; // Wow, this is ugly

    Console.WriteLine($"I, the thread write: {message}");
}



Casting is something you typically do not want to do.

What if someone passes something else which is not a string? As this seems not possible at first (because It is my method, I know what I do or The method is private, how should someone ever be able to pass anything to it?) you may possibly end up with exactly that case for various reasons. As some cases may not be a problem, others are. In such cases you will probably end up with an InvalidCastException which you probably will not notice because it simply terminates the thread.

As a solution you would expect to get a generic ParameterizedThreadStart delegate like ParameterizedThreadStart<T> where T would be the type of data you want to pass into the Work method. Unfortunately something like this does not exist (yet?).

There is however a suggested solution to this issue. It involves creating a class which contains both, the data to be passed to the thread as well as the method that represents the worker method like this:

public class ThreadWithState
{
    private string message;

    public ThreadWithState(string message)
    {
        this.message = message;
    }

    public void Work()
    {
        Console.WriteLine($"I, the thread write: {this.message}");
    }
}

With this approach you would start the thread like this:

ThreadWithState tws = new ThreadWithState("I've got some text");
Thread thread = new Thread(tws.Work);

thread.Start();

So in this way you simply avoid casting around and have a typesafe way of providing data to a thread ;-)

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

How can I determine if a date is between two dates in Java?

import java.util.Date;

public class IsDateBetween {

public static void main (String[] args) {

          IsDateBetween idb=new IsDateBetween("12/05/2010"); // passing your Date
 }
 public IsDateBetween(String dd) {

       long  from=Date.parse("01/01/2000");  // From some date

       long to=Date.parse("12/12/2010");     // To Some Date

       long check=Date.parse(dd);

       int x=0;

      if((check-from)>0 && (to-check)>0)
      {
             x=1;
      }

 System.out.println ("From Date is greater Than  ToDate : "+x);
}   

}

How to set up default schema name in JPA configuration?

For those who uses last versions of spring boot will help this:

.properties:

spring.jpa.properties.hibernate.default_schema=<name of your schema>

.yml:

spring:
    jpa:
        properties:
            hibernate:
                default_schema: <name of your schema>

Django datetime issues (default=datetime.now())

From the Python language reference, under Function definitions:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call.

Fortunately, Django has a way to do what you want, if you use the auto_now argument for the DateTimeField:

date = models.DateTimeField(auto_now=True)

See the Django docs for DateTimeField.

Hide all elements with class using plain Javascript

In the absence of jQuery, I would use something like this:

<script>
    var divsToHide = document.getElementsByClassName("classname"); //divsToHide is an array
    for(var i = 0; i < divsToHide.length; i++){
        divsToHide[i].style.visibility = "hidden"; // or
        divsToHide[i].style.display = "none"; // depending on what you're doing
    }
<script>

This is taken from this SO question: Hide div by class id, however seeing that you're asking for "old-school" JS solution, I believe that getElementsByClassName is only supported by modern browsers

Connection Strings for Entity Framework

Instead of using config files you can use a configuration database with a scoped systemConfig table and add all your settings there.

CREATE TABLE [dbo].[SystemConfig]  
    (  
      [Id] [int] IDENTITY(1, 1)  
                 NOT NULL ,  
      [AppName] [varchar](128) NULL ,  
      [ScopeName] [varchar](128) NOT NULL ,  
      [Key] [varchar](256) NOT NULL ,  
      [Value] [varchar](MAX) NOT NULL ,  
      CONSTRAINT [PK_SystemConfig_ID] PRIMARY KEY NONCLUSTERED ( [Id] ASC )  
        WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
               IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,  
               ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]  
    )  
ON  [PRIMARY]  

GO  

SET ANSI_PADDING OFF  
GO  

ALTER TABLE [dbo].[SystemConfig] ADD  CONSTRAINT [DF_SystemConfig_ScopeName]  DEFAULT ('SystemConfig') FOR [ScopeName]  
GO 

With such configuration table you can create rows like such: enter image description here

Then from your your application dal(s) wrapping EF you can easily retrieve the scoped configuration.
If you are not using dal(s) and working in the wire directly with EF, you can make an Entity from the SystemConfig table and use the value depending on the application you are on.

How to find the width of a div using vanilla JavaScript?

You can use clientWidth or offsetWidth Mozilla developer network reference

It would be like:

document.getElementById("yourDiv").clientWidth; // returns number, like 728

or with borders width :

document.getElementById("yourDiv").offsetWidth; // 728 + borders width

MySQL Error 1093 - Can't specify target table for update in FROM clause

how about this query hope it helps

DELETE FROM story_category LEFT JOIN (SELECT category.id FROM category) cat ON story_category.id = cat.id WHERE cat.id IS NULL

Is there a way to create and run javascript in Chrome?

You need an HTML page to load a JS file.

NSAttributedString add text alignment

 NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
 paragraphStyle.alignment                = NSTextAlignmentCenter;

 NSAttributedString *attributedString   = 
[NSAttributedString.alloc initWithString:@"someText" 
                              attributes:
         @{NSParagraphStyleAttributeName:paragraphStyle}];

Swift 4.2

let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.center

    let attributedString = NSAttributedString(string: "someText", attributes: [NSAttributedString.Key.paragraphStyle : paragraphStyle])

How to export html table to excel or pdf in php

Easiest way to export Excel to Html table

$file_name ="file_name.xls";
$excel_file="Your Html Table Code";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file_name");
echo $excel_file;

How to scroll table's "tbody" independent of "thead"?

thead {
  position: fixed;
  height: 10px; /* This is whatever height you want */
}
  tbody {
  position: fixed;
  margin-top: 10px; /* This has to match the height of thead */
  height: 300px; /* This is whatever height you want */
}

Copy existing project with a new name in Android Studio

In android studio 4.1.1:

Step 1 You copy the project in the file explorer and give it a new name.

Step 2 Open the copied project in the android studio and go to the Gradle Scrips files and change the name of the project to the new name in the settings and build files.

Step 3 Go to the properties Gradle file and add the line: android.overridePathCheck=true

What is the difference between Collection and List in Java?

Collection is the Super interface of List so every Java list is as well an instance of collection. Collections are only iterable sequentially (and in no particular order) whereas a List allows access to an element at a certain position via the get(int index) method.

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Don't worry! This problem occurs because of the annotation. Instead of Field based access, Property based access solves this problem. The code as follows:

package onetomanymapping;

import java.util.List;

import javax.persistence.*;

@Entity
public class College {
private int collegeId;
private String collegeName;
private List<Student> students;

@OneToMany(targetEntity = Student.class, mappedBy = "college", 
    cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Student> getStudents() {
    return students;
}

public void setStudents(List<Student> students) {
    this.students = students;
}

@Id
@GeneratedValue
public int getCollegeId() {
    return collegeId;
}

public void setCollegeId(int collegeId) {
    this.collegeId = collegeId;
}

public String getCollegeName() {
    return collegeName;
}

public void setCollegeName(String collegeName) {
    this.collegeName = collegeName;
}

}

SFTP in Python? (platform independent)

fsspec is a great option for this, it offers a filesystem like implementation of sftp.

from fsspec.implementations.sftp import SFTPFileSystem
fs = SFTPFileSystem(host=host, username=username, password=password)

# list a directory
fs.ls("/")

# open a file
with fs.open(file_name) as file:
    content = file.read()

Also worth noting that fsspec uses paramiko in the implementation.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

Import base.py in __init__.py alone. make sure you won't repeat the same configuration again!.

set environment variable SET DJANGO_DEVELOPMENT =dev

settings/
  __init__.py
  base.py
  local.py
  production.py

In __init__.py

from .base import *
if os.environ.get('DJANGO_DEVELOPMENT')=='prod':
   from .production import *
else:
   from .local import *

In base.py configured the global configurations. except for Database. like

SECRET_KEY, ALLOWED_HOSTS,INSTALLED_APPS,MIDDLEWARE .. etc....

In local.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'database',
    'USER': 'postgres',
    'PASSWORD': 'password',
    'HOST': 'localhost',
    'PORT': '5432',
}
}

Java: Difference between the setPreferredSize() and setSize() methods in components

setSize will resize the component to the specified size.

setPreferredSize sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.

need to test if sql query was successful

if the value is 0 then it wasn't successful, but if 1 then successful.

$this->db->affected_rows();

Display label text with line breaks in c#

Following line worked for me:

lbTabRes.Text += num + " x " + i + " = " + (num * i).ToString() + "<br/> \n";

How to add an image in Tkinter?

It's a Python version problem. If you are using the latest, then your old syntax won't work and give you this error. Please follow @Josav09's code and you will be fine.

"Submit is not a function" error in JavaScript

What I used is

var enviar = document.getElementById("enviar");
enviar.type = "submit"; 

Just because everything else didn´t work.

What does .class mean in Java?

Class is a parameterizable class, hence you can use the syntax Class<T> where T is a type. By writing Class<?>, you're declaring a Class object which can be of any type (? is a wildcard). The Class type is a type that contains meta-information about a class.

It's always good practice to refer to a generic type by specifying his specific type, by using Class<?> you're respecting this practice (you're aware of Class to be parameterizable) but you're not restricting your parameter to have a specific type.

Reference about Generics and Wildcards: http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html

Reference about Class object and reflection (the feature of Java language used to introspect itself): https://www.oracle.com/technetwork/articles/java/javareflection-1536171.html

git - Server host key not cached

Rene, your HOME variable isn't set correctly. Either change it to c:\Users\(your-username) or just to %USERNAME%.

Choosing the default value of an Enum type without having to change values

If zero doesn't work as the proper default value, you can use the component model to define a workaround for the enum:

[DefaultValue(None)]
public enum Orientation
{
     None = -1,
     North = 0,
     East = 1,
     South = 2,
     West = 3
 }

public static class Utilities
{
    public static TEnum GetDefaultValue<TEnum>() where TEnum : struct
    {
        Type t = typeof(TEnum);
        DefaultValueAttribute[] attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);
        if (attributes != null &&
            attributes.Length > 0)
        {
            return (TEnum)attributes[0].Value;
        }
        else
        {
            return default(TEnum);
        }
    }
}

and then you can call:

Orientation o = Utilities.GetDefaultValue<Orientation>();
System.Diagnostics.Debug.Print(o.ToString());

Note: you will need to include the following line at the top of the file:

using System.ComponentModel;

This does not change the actual C# language default value of the enum, but gives a way to indicate (and get) the desired default value.

Where is android studio building my .apk file?

After compiling my code in Android Studio, I found it here:

~\MyApp_Name\app\build\outputs\apk\app-debug.apk

How do you round a floating point number in Perl?

loads of reading documentation on how to round numbers, many experts suggest writing your own rounding routines, as the 'canned' version provided with your language may not be precise enough, or contain errors. i imagine, however, they're talking many decimal places not just one, two, or three. with that in mind, here is my solution (although not EXACTLY as requested as my needs are to display dollars - the process is not much different, though).

sub asDollars($) {
  my ($cost) = @_;
  my $rv = 0;

  my $negative = 0;
  if ($cost =~ /^-/) {
    $negative = 1;
    $cost =~ s/^-//;
  }

  my @cost = split(/\./, $cost);

  # let's get the first 3 digits of $cost[1]
  my ($digit1, $digit2, $digit3) = split("", $cost[1]);
  # now, is $digit3 >= 5?
  # if yes, plus one to $digit2.
  # is $digit2 > 9 now?
  # if yes, $digit2 = 0, $digit1++
  # is $digit1 > 9 now??
  # if yes, $digit1 = 0, $cost[0]++
  if ($digit3 >= 5) {
    $digit3 = 0;
    $digit2++;
    if ($digit2 > 9) {
      $digit2 = 0;
      $digit1++;
      if ($digit1 > 9) {
        $digit1 = 0;
        $cost[0]++;
      }
    }
  }
  $cost[1] = $digit1 . $digit2;
  if ($digit1 ne "0" and $cost[1] < 10) { $cost[1] .= "0"; }

  # and pretty up the left of decimal
  if ($cost[0] > 999) { $cost[0] = commafied($cost[0]); }

  $rv = join(".", @cost);

  if ($negative) { $rv = "-" . $rv; }

  return $rv;
}

sub commafied($) {
  #*
  # to insert commas before every 3rd number (from the right)
  # positive or negative numbers
  #*
  my ($num) = @_; # the number to insert commas into!

  my $negative = 0;
  if ($num =~ /^-/) {
    $negative = 1;
    $num =~ s/^-//;
  }
  $num =~ s/^(0)*//; # strip LEADING zeros from given number!
  $num =~ s/0/-/g; # convert zeros to dashes because ... computers!

  if ($num) {
    my @digits = reverse split("", $num);
    $num = "";

    for (my $i = 0; $i < @digits; $i += 3) {
      $num .= $digits[$i];
      if ($digits[$i+1]) { $num .= $digits[$i+1]; }
      if ($digits[$i+2]) { $num .= $digits[$i+2]; }
      if ($i < (@digits - 3)) { $num .= ","; }
      if ($i >= @digits) { last; }
    }

    #$num =~ s/,$//;
    $num = join("", reverse split("", $num));
    $num =~ s/-/0/g;
  }

  if ($negative) { $num = "-" . $num; }

  return $num; # a number with commas added
  #usage: my $prettyNum = commafied(1234567890);
}

Jquery - How to get the style display attribute "none / block"

You could try:

$j('div.contextualError.ckgcellphone').css('display')

Mouseover or hover vue.js

I came up with the same problem, and I work it out !

_x000D_
_x000D_
        <img :src='book.images.small' v-on:mouseenter="hoverImg">
_x000D_
_x000D_
_x000D_

Generate insert script for selected records?

If you are using Oracle SQL Developer then it would be

select /*insert*/ * from TABLE_NAME where COLUMN_NAME = 'VALUE';

Run this as a script

How to scale Docker containers in production

A sensible approach to scaling Docker could be:

  1. Each service will be a docker container
  2. Intra container service discovery managed through links (new feature from docker 0.6.5)
  3. Containers will be deployed through Dokku
  4. Applications will be managed through Shipyard which in its turn is using hipache

Another docker open sourced project from Yandex:

Hiding a form and showing another when a button is clicked in a Windows Forms application

private void button5_Click(object sender, EventArgs e)
{
    this.Visible = false;
    Form2 login = new Form2();
    login.ShowDialog();
}

Find something in column A then show the value of B for that row in Excel 2010

Guys Its very interesting to know that many of us face the problem of replication of lookup value while using the Vlookup/Index with Match or Hlookup.... If we have duplicate value in a cell we all know, Vlookup will pick up against the first item would be matching in loopkup array....So here is solution for you all...

e.g.

in Column A we have field called company....

Column A                             Column B            Column C

Company_Name                         Value        
Monster                              25000                              
Naukri                               30000  
WNS                                  80000  
American Express                     40000  
Bank of America                      50000  
Alcatel Lucent                       35000  
Google                               75000  
Microsoft                            60000  
Monster                              35000  
Bank of America                      15000 

Now if you lookup the above dataset, you would see the duplicity is in Company Name at Row No# 10 & 11. So if you put the vlookup, the data will be picking up which comes first..But if you use the below formula, you can make your lookup value Unique and can pick any data easily without having any dispute or facing any problem

Put the formula in C2.........A2&"_"&COUNTIF(A2:$A$2,A2)..........Result will be Monster_1 for first line item and for row no 10 & 11.....Monster_2, Bank of America_2 respectively....Here you go now you have the unique value so now you can pick any data easily now..

Cheers!!! Anil Dhawan

Numpy, multiply array with scalar

Using .multiply() (ufunc multiply)

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0 

np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])

How do you run a command for each line of a file?

If you want to run your command in parallel for each line you can use GNU Parallel

parallel -a <your file> <program>

Each line of your file will be passed to program as an argument. By default parallel runs as many threads as your CPUs count. But you can specify it with -j

How to access iOS simulator camera

It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS version and any Simulator. You will have to use device for testing camera purpose.

Node.js - EJS - including a partial

In oficial documentation https://github.com/mde/ejs#includes show that includes works like that:

<%- include('../partials/head') %>

How to scan a folder in Java?

public static void directory(File dir) {
    File[] files = dir.listFiles();
    for (File file : files) {
        System.out.println(file.getAbsolutePath());
        if (file.listFiles() != null)
            directory(file);        
    }
} 

Here dir is Directory to be scanned. e.g. c:\

Add object to ArrayList at specified index

If that's the case then why don't you consider using a regular Array, initialize the capacity and put objects at the index you want.

Object[] list = new Object[10];

list[0] = object1;
list[2] = object3;
list[1] = object2;

Consistency of hashCode() on a Java string

Another (!) issue to worry about is the possible change of implementation between early/late versions of Java. I don't believe the implementation details are set in stone, and so potentially an upgrade to a future Java version could cause problems.

Bottom line is, I wouldn't rely on the implementation of hashCode().

Perhaps you can highlight what problem you're actually trying to solve by using this mechanism, and that will highlight a more suitable approach.

Getting Textarea Value with jQuery

change id="#message" to id="message" on your textarea element.

and by the way, just use this:

$('#send-thoughts')

remember that you should only use ID's once and you can use classes over and over.

https://css-tricks.com/the-difference-between-id-and-class/

Getting value GET OR POST variable using JavaScript?

Here is my answer for this given a string returnURL which is like http://host.com/?param1=abc&param2=cde. It's fairly basic as I'm beginning at JavaScript (this is actually part of my first program ever in JS), and making it simpler to understand rather than tricky.

Notes

  • No sanity checking of values
  • Just outputting to the console - you'll want to store them in an array or something
  • this is only for GET, and not POST

    var paramindex = returnURL.indexOf('?');
    if (paramindex > 0) {
        var paramstring = returnURL.split('?')[1];
        while (paramindex > 0) {
            paramindex = paramstring.indexOf('=');
            if (paramindex > 0) {
                var parkey = paramstring.substr(0,paramindex);
                console.log(parkey)
                paramstring = paramstring.substr(paramindex+1) // +1 to strip out the =
            }
            paramindex = paramstring.indexOf('&');
            if (paramindex > 0) {
                var parvalue = paramstring.substr(0,paramindex);
                console.log(parvalue)
                paramstring = paramstring.substr(paramindex+1) // +1 to strip out the &
            } else { // we're at the end of the URL
                var parvalue = paramstring
                console.log(parvalue)
                break;
            }
        }
    }
    

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

Windows must be created on the same stack (aka microtask) as the user-initiated event, e.g. a click callback--so they can't be created later, asynchronously.

However, you can create a window without a URL and you can then change that window's URL once you do know it, even asynchronously!

window.onclick = () => {
  // You MUST create the window on the same event
  // tick/stack as the user-initiated event (e.g. click callback)
  const googleWindow = window.open();

  // Do your async work
  fakeAjax(response => {
    // Change the URL of the window you created once you
    // know what the full URL is!
    googleWindow.location.replace(`https://google.com?q=${response}`);
  });
};

function fakeAjax(callback) {
  setTimeout(() => {
    callback('example');
  }, 1000);
}

Modern browsers will open the window with a blank page (often called about:blank), and assuming your async task to get the URL is fairly quick, the resulting UX is mostly fine. If you instead want to render a loading message (or anything) into the window while the user waits, you can use Data URIs.

window.open('data:text/html,<h1>Loading...<%2Fh1>');

Choosing line type and color in Gnuplot 4.0

I've ran into this topic, because i was struggling with dashed lines too (gnuplot 4.6 patchlevel 0)

If you use:

set termoption dashed

Your posted code will work accordingly.

Related question:
However, if I want to export a png with: set terminal png, this isn't working anymore. Anyone got a clue why?

Turns out, out, gnuplots png export library doesnt support this.
Possbile solutions:

  • one can simply export to ps, then convert it with pstopng
  • according to @christoph, if you use pngcairo as your terminal (set terminal pngcairo) it will work

PHP/MySQL Insert null values

For fields where NULL is acceptable, you could use var_export($var, true) to output the string, integer, or NULL literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.

For example:

mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");

C# constructors overloading

You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

Example:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}

SpringApplication.run main method

You need to run Application.run() because this method starts whole Spring Framework. Code below integrates your main() with Spring Boot.

Application.java

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

ReconTool.java

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        main(args);
    }

    public static void main(String[] args) {
        // Recon Logic
    }
}

Why not SpringApplication.run(ReconTool.class, args)

Because this way spring is not fully configured (no component scan etc.). Only bean defined in run() is created (ReconTool).

Example project: https://github.com/mariuszs/spring-run-magic

Remove characters from C# string

Lots of good answers here, here's my addition along with several unit tests that can be used to help test correctness, my solution is similar to @Rianne's above but uses an ISet to provide O(1) lookup time on the replacement characters (and also similar to @Albin Sunnanbo's Linq solution).

    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Returns a string with the specified characters removed.
    /// </summary>
    /// <param name="source">The string to filter.</param>
    /// <param name="removeCharacters">The characters to remove.</param>
    /// <returns>A new <see cref="System.String"/> with the specified characters removed.</returns>
    public static string Remove(this string source, IEnumerable<char> removeCharacters)
    {
        if (source == null)
        {
            throw new  ArgumentNullException("source");
        }

        if (removeCharacters == null)
        {
            throw new ArgumentNullException("removeCharacters");
        }

        // First see if we were given a collection that supports ISet
        ISet<char> replaceChars = removeCharacters as ISet<char>;

        if (replaceChars == null)
        {
            replaceChars = new HashSet<char>(removeCharacters);
        }

        IEnumerable<char> filtered = source.Where(currentChar => !replaceChars.Contains(currentChar));

        return new string(filtered.ToArray());
    }

NUnit (2.6+) tests here

using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;

[TestFixture]
public class StringExtensionMethodsTests
{
    [TestCaseSource(typeof(StringExtensionMethodsTests_Remove_Tests))]
    public void Remove(string targetString, IEnumerable<char> removeCharacters, string expected)
    {
        string actual = StringExtensionMethods.Remove(targetString, removeCharacters);

        Assert.That(actual, Is.EqualTo(expected));
    }

    [TestCaseSource(typeof(StringExtensionMethodsTests_Remove_ParameterValidation_Tests))]
    public void Remove_ParameterValidation(string targetString, IEnumerable<char> removeCharacters)
    {
        Assert.Throws<ArgumentNullException>(() => StringExtensionMethods.Remove(targetString, removeCharacters));
    }
}

internal class StringExtensionMethodsTests_Remove_Tests : IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        yield return new TestCaseData("My name @is ,Wan.;'; Wan", new char[] { '@', ',', '.', ';', '\'' }, "My name is Wan Wan").SetName("StringUsingCharArray");
        yield return new TestCaseData("My name @is ,Wan.;'; Wan", new HashSet<char> { '@', ',', '.', ';', '\'' }, "My name is Wan Wan").SetName("StringUsingISetCollection");
        yield return new TestCaseData(string.Empty, new char[1], string.Empty).SetName("EmptyStringNoReplacementCharactersYieldsEmptyString");
        yield return new TestCaseData(string.Empty, new char[] { 'A', 'B', 'C' }, string.Empty).SetName("EmptyStringReplacementCharsYieldsEmptyString");
        yield return new TestCaseData("No replacement characters", new char[1], "No replacement characters").SetName("StringNoReplacementCharactersYieldsString");
        yield return new TestCaseData("No characters will be replaced", new char[] { 'Z' }, "No characters will be replaced").SetName("StringNonExistantReplacementCharactersYieldsString");
        yield return new TestCaseData("AaBbCc", new char[] { 'a', 'C' }, "ABbc").SetName("CaseSensitivityReplacements");
        yield return new TestCaseData("ABC", new char[] { 'A', 'B', 'C' }, string.Empty).SetName("AllCharactersRemoved");
        yield return new TestCaseData("AABBBBBBCC", new char[] { 'A', 'B', 'C' }, string.Empty).SetName("AllCharactersRemovedMultiple");
        yield return new TestCaseData("Test That They Didn't Attempt To Use .Except() which returns distinct characters", new char[] { '(', ')' }, "Test That They Didn't Attempt To Use .Except which returns distinct characters").SetName("ValidateTheStringIsNotJustDistinctCharacters");
    }
}

internal class StringExtensionMethodsTests_Remove_ParameterValidation_Tests : IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        yield return new TestCaseData(null, null);
        yield return new TestCaseData("valid string", null);
        yield return new TestCaseData(null, new char[1]);
    }
}

Return Type for jdbcTemplate.queryForList(sql, object, classType)

A complete solution for JdbcTemplate, NamedParameterJdbcTemplate with or without RowMapper Example.

// Create a Employee table

create table employee(  
id number(10),  
name varchar2(100),  
salary number(10)  
);

======================================================================= //Employee.java

public class Employee {
private int id;  
private String name;  
private float salary;  

//no-arg and parameterized constructors  

public Employee(){};

public Employee(int  id, String name, float salary){
    this.id=id;
    this.name=name;
    this.salary=salary;
}

//getters and setters  
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public float getSalary() {
    return salary;
}
public void setSalary(float salary) {
    this.salary = salary;
}
public String toString(){  
   return id+" "+name+" "+salary;  
}   

}

========================================================================= //EmployeeDao.java

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class EmployeeDao {  
  private JdbcTemplate jdbcTemplate;  
  private NamedParameterJdbcTemplate nameTemplate;  

  public void setnameTemplate(NamedParameterJdbcTemplate template) {  
    this.nameTemplate = template;  
 }   

 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
  this.jdbcTemplate = jdbcTemplate;  
 }  

 // BY using JdbcTemplate
 public int saveEmployee(Employee e){  
 int id = e.getId();
 String name = e.getName();
 float salary = e.getSalary();
 Object p[] = {id, name, salary};
    String query="insert into employee values(?,?,?)";
      return jdbcTemplate.update(query, p);
    /*String query="insert into employee     values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')"; 
      return jdbcTemplate.update(query);
    */

}  

//By using NameParameterTemplate
public void insertEmploye(Employee e) {  
String query="insert into employee values (:id,:name,:salary)";  
Map<String,Object> map=new HashMap<String,Object>();  
map.put("id",e.getId());  
map.put("name",e.getName());  
map.put("salary",e.getSalary());  

nameTemplate.execute(query,map,new MyPreparedStatement());

 }
// Updating Employee
public int updateEmployee(Employee e){  
String query="update employee set  name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
  return jdbcTemplate.update(query);  
 }
 // Deleting a Employee row
 public int deleteEmployee(Employee e){  
 String query="delete from employee where id='"+e.getId()+"' ";  
 return jdbcTemplate.update(query);  
 }  
 //Selecting Single row with condition and also all rows
    public int selectEmployee(Employee e){  
     //String query="select * from employee where id='"+e.getId()+"' ";
      String query="select * from employee";
      List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
       for(Map<String, Object> row : rows){
          String id = row.get("id").toString();
          String name = (String)row.get("name");
          String salary = row.get("salary").toString();
          System.out.println(id + " " + name + " " + salary );
        }

      return 1;
   }  

   // Can use MyrowMapper class an implementation class for RowMapper interface
    public void getAllEmployee()
    {

    String query="select * from employee";
    List<Employee> l = jdbcTemplate.query(query, new MyrowMapper());

    Iterator it=l.iterator();
    while(it.hasNext())
    {
      Employee e=(Employee)it.next();
      System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
    }
   }  

  //Can use directly a RowMapper implementation class without an object creation
  public List<Employee> getAllEmployee1(){
    return jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){  
      @Override  
      public Employee mapRow(ResultSet rs, int rownumber) throws  SQLException    {  
            Employee e=new Employee();  
            e.setId(rs.getInt(1));  
            e.setName(rs.getString(2));  
            e.setSalary(rs.getFloat(3));  
            return e;  
          }  
      });  
      }
     // End of all the function

     }

================================================================ //MyrowMapper.java

 import java.sql.ResultSet;
 import java.sql.SQLException;
 import org.springframework.jdbc.core.RowMapper;

 public class MyrowMapper implements RowMapper<Employee> {

  @Override  
  public Employee mapRow(ResultSet rs, int rownumber) throws SQLException 
   {  
    System.out.println("mapRow()====:"+rownumber);
    Employee e=new Employee();  
     e.setId(rs.getInt("id"));  
     e.setName(rs.getString("name"));  
     e.setSalary(rs.getFloat("salary"));  
     return e;  
      }
    } 

========================================================== //MyPreparedStatement.java

import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;


 public class MyPreparedStatement implements  PreparedStatementCallback<Object> {

 @Override
 public Object doInPreparedStatement(PreparedStatement ps)
        throws SQLException, DataAccessException {

     return ps.executeUpdate(); 
  } 

 } 

===================================================================== //Test.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {  

public static void main(String[] args) {  
 ApplicationContext ctx=new     ClassPathXmlApplicationContext("applicationContext.xml");  

 EmployeeDao dao=(EmployeeDao)ctx.getBean("edao"); 

  // By calling constructor for insert
 /* 
    int status=dao.saveEmployee(new Employee(103,"Ajay",35000));  
    System.out.println(status);  
 */
 // By calling PreparedStatement
  dao.insertEmploye(new Employee(103,"Roh",25000));


 // By calling setter-getter for update
 /* 
    Employee e=new Employee(); 
    e.setId(102);
    e.setName("Rohit");
    e.setSalary(8000000);
    int status=dao.updateEmployee(e);
*/
 // By calling constructor for update
 /*
    int status=dao.updateEmployee(new Employee(102,"Sadhan",15000)); 
    System.out.println(status); 
 */ 
 // Deleting a record 
 /*      
    Employee e=new Employee(); 
    e.setId(102); 
    int status=dao.deleteEmployee(e); 
    System.out.println(status);
 */
 // Selecting single or all rows
 /*
    Employee e=new Employee(); 
    e.setId(102);
    int status=dao.selectEmployee(e);
    System.out.println(status);
*/
// Can use MyrowMapper class an implementation class for RowMapper interface

    dao.getAllEmployee();

// Can use directly a RowMapper implementation class without an object creation
 /*
    List<Employee> list=dao.getAllEmployee1();  
    for(Employee e1:list)  
    System.out.println(e1);  
  */   
   }  

 } 

================================================================== //applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
 xmlns="http://www.springframework.org/schema/beans"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans   
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

<bean id="ds"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
 <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />  
 <property name="username" value="hr" />  
 <property name="password" value="hr" />  
 </bean>  

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
 <property name="dataSource" ref="ds"></property>  
 </bean>  

<bean id="nameTemplate"   
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
<constructor-arg ref="ds"></constructor-arg>  
</bean>  

<bean id="edao" class="EmployeeDao"> 
<!-- Can use both --> 
<property name="nameTemplate" ref="nameTemplate"></property>
<property name="jdbcTemplate" ref="jdbcTemplate"></property> 
</bean>  

===================================================================

Get table names using SELECT statement in MySQL

To get the name of all tables use:

SELECT table_name FROM information_schema.tables;

To get the name of the tables from a specific database use:

SELECT table_name FROM information_schema.tables
WHERE table_schema = 'your_database_name';

Now, to answer the original question, use this query:

INSERT INTO table_name
    SELECT table_name FROM information_schema.tables
        WHERE table_schema = 'your_database_name';

For more details see: http://dev.mysql.com/doc/refman/5.0/en/information-schema.html

Copy entire contents of a directory to another using php

I clone entire directory by SPL Directory Iterator.

function recursiveCopy($source, $destination)
{
    if (!file_exists($destination)) {
        mkdir($destination);
    }

    $splFileInfoArr = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($splFileInfoArr as $fullPath => $splFileinfo) {
        //skip . ..
        if (in_array($splFileinfo->getBasename(), [".", ".."])) {
            continue;
        }
        //get relative path of source file or folder
        $path = str_replace($source, "", $splFileinfo->getPathname());

        if ($splFileinfo->isDir()) {
            mkdir($destination . "/" . $path);
        } else {
        copy($fullPath, $destination . "/" . $path);
        }
    }
}
#calling the function
recursiveCopy(__DIR__ . "/source", __DIR__ . "/destination");

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

@RequestBody and @ResponseBody annotations in Spring

@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request.

For example:

@RequestMapping(path = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
    writer.write(body);
}

@ResponseBody annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).

For example:

@RequestMapping(path = "/something", method = RequestMethod.PUT)
public  @ResponseBody String helloWorld() {
    return "Hello World";
}  

Alternatively, we can use @RestController annotation in place of @Controller annotation. This will remove the need to using @ResponseBody.

for more details

VBScript How can I Format Date?

The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.

If you want your output to be "culture invariant", use myDateFormat() from stian.net's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use

Replace(FormatDateTime(d,2),"/","-")

How to create a custom navigation drawer in android

You can easily customize the android Navigation drawer once you know how its implemented. here is a nice tutorial where you can set it up.

This will be the structure of your mainXML:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Framelayout to display Fragments -->
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Listview to display slider menu -->
    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"        
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>

You can customize this listview to your liking by adding the header. And radiobuttons.

How to recursively find the latest modified file in a directory?

To search for files in /target_directory and all its sub-directories, that have been modified in the last 60 minutes:

$ find /target_directory -type f -mmin -60

To find the most recently modified files, sorted in the reverse order of update time (i.e., the most recently updated files first):

$ find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r

How to add click event to a iframe with JQuery

Solution that work for me :

var editorInstance = CKEDITOR.instances[this.editorId];

            editorInstance.on('focus', function(e) {

                console.log("tadaaa");

            });

Entity framework code-first null foreign key

I have the same problem now , I have foreign key and i need put it as nullable, to solve this problem you should put

    modelBuilder.Entity<Country>()
        .HasMany(c => c.Users)
        .WithOptional(c => c.Country)
        .HasForeignKey(c => c.CountryId)
        .WillCascadeOnDelete(false);

in DBContext class I am sorry for answer you very late :)

TypeError: 'dict' object is not callable

The syntax for accessing a dict given a key is number_map[int(x)]. number_map(int(x)) would actually be a function call but since number_map is not a callable, an exception is raised.

How to send email from MySQL 5.1

I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.

It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.

How to add a column in TSQL after a specific column?

Unfortunately you can't.

If you really want them in that order you'll have to create a new table with the columns in that order and copy data. Or rename columns etc. There is no easy way.

Run a controller function whenever a view is opened/shown

I faced at the same problem, and here i leave the reason of this behavior for everyone else with the same issue.

View LifeCycle

In order to improve performance, we've improved Ionic's ability to cache view elements and scope data. Once a controller is initialized, it may persist throughout the app’s life; it’s just hidden and removed from the watch cycle. Since we aren’t rebuilding scope, we’ve added events for which we should listen when entering the watch cycle again.

To see full description and $ionicView events go to: http://ionicframework.com/blog/navigating-the-changes/

Implement touch using Python?

It might seem logical to create a string with the desired variables, and pass it to os.system:

touch = 'touch ' + dir + '/' + fileName
os.system(touch)

This is inadequate in a number of ways (e.g.,it doesn't handle whitespace), so don't do it.

A more robust method is to use subprocess :

subprocess.call(['touch', os.path.join(dirname, fileName)])

While this is much better than using a subshell (with os.system), it is still only suitable for quick-and-dirty scripts; use the accepted answer for cross-platform programs.

Python function global variables?

You must use the global declaration when you wish to alter the value assigned to a global variable.

You do not need it to read from a global variable. Note that calling a method on an object (even if it alters the data within that object) does not alter the value of the variable holding that object (absent reflective magic).

Setting the value of checkbox to true or false with jQuery

<input type="checkbox" name="vehicle" id="vehicleChkBox" value="FALSE"/>

--

$('#vehicleChkBox').change(function(){
    if(this.checked)
        $('#vehicleChkBox').val('TRUE');
   else
        $('#vehicleChkBox').val('False');
});

How to serialize an object to XML without getting xmlns="..."?

Ahh... nevermind. It's always the search after the question is posed that yields the answer. My object that is being serialized is obj and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.

In VB like this:

Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")

Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True

Using ms As New MemoryStream(), _
    sw As XmlWriter = XmlWriter.Create(ms, settings), _
    sr As New StreamReader(ms)
xs.Serialize(sw, obj, ns)
ms.Position = 0
Console.WriteLine(sr.ReadToEnd())
End Using

in C# like this:

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.

Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.

So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.

With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).

Portable way to get file size (in bytes) in shell?

I ended up writing my own program (really small) to display just the size. More information here: http://fwhacking.blogspot.com/2011/03/bfsize-print-file-size-in-bytes-and.html

The two most clean ways in my opinion with common Linux tools are:

$ stat -c %s /usr/bin/stat
50000

$ wc -c < /usr/bin/wc
36912

But I just don't want to be typing parameters or pipe the output just to get a file size, so I'm using my own bfsize.

Facebook Android Generate Key Hash

I was able to do perform the requested task with some of the solutions here, but thought to myself, boy that is stupid... why not to write a small Java code that does this and pack it into a Jar, so I did...

A link to download the Jar

Works on Windows 8... didn't try any other OS.

XML Parsing - Read a Simple XML File and Retrieve Values

class Program
{

    static void Main(string[] args)
    {

        //Load XML from local
        string sourceFileName="";
        string element=string.Empty;
        var FolderPath=@"D:\Test\RenameFileWithXmlAttribute";

            string[] files = Directory.GetFiles(FolderPath, "*.xml");
            foreach (string xmlfile in files)
            {
                try
                {
                    sourceFileName = xmlfile;
                    XElement xele = XElement.Load(sourceFileName);
                    string convertToString = xele.ToString();
                    XElement parseXML = XElement.Parse(convertToString);
                    element = parseXML.Descendants("Meta").Where(x => (string)x.Attribute("name") == "XMLTAG").Last().Value;
                    DirectoryInfo CurrentDate = Directory.CreateDirectory(DateTime.Now.ToString("yyyy-MM-dd"));
                    string saveWithThisName= Path.Combine(CurrentDate.FullName, element);
                    File.Copy(sourceFileName, saveWithThisName,true);                      
                }
                catch(Exception ex)
                {

                }      
            }       
    }
}

How to scanf only integer and repeat reading if the user enters non-numeric characters?

You could create a function that reads an integer between 1 and 23 or returns 0 if non-int

e.g.

int getInt()
{
  int n = 0;
  char buffer[128];
  fgets(buffer,sizeof(buffer),stdin);
  n = atoi(buffer); 
  return ( n > 23 || n < 1 ) ? 0 : n;
}

Does it make sense to use Require.js with Angular.js?

Yes it makes sense to use angular.js along with require.js wherein you can use require.js for modularizing components.

There is a seed project which uses both angular.js and require.js.

Is it possible to use 'else' in a list comprehension?

Great answers, but just wanted to mention a gotcha that "pass" keyword will not work in the if/else part of the list-comprehension (as posted in the examples mentioned above).

#works
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else x**2 for x in list1 ]
print(newlist2, type(newlist2))

#but this WONT work
list1 = [10, 20, 30, 40, 50]
newlist2 = [x if x > 30 else pass for x in list1 ]
print(newlist2, type(newlist2))

This is tried and tested on python 3.4. Error is as below:

newlist2 = [x if x > 30 else pass for x in list1 ]                                    
SyntaxError: invalid syntax

So, try to avoid pass-es in list comprehensions

Fill an array with random numbers

This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!

  • Think about a construct that can help you iterate over the array. Is there some sort of construct (a loop perhaps?) that you can use to iterate over each location in the array?
  • Within this construct, for each iteration of the loop, you will assign the value returned by randomFill() to the current location of the array.

Note: Your array is double, but you are returning ints from randomFill. So there's something you need to fix there.

ImageView in circular through xml

Just use the ShapeableImageView provided by the Material Components Library.
Somethig like:

<com.google.android.material.imageview.ShapeableImageView
    app:shapeAppearanceOverlay="@style/roundedImageViewRounded"
    app:strokeColor="@color/....."
    app:strokeWidth="1dp"
    ...
    />

with:

  <style name="roundedImageViewRounded">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
  </style>

enter image description here

Note: it requires at least the version 1.2.0-alpha03.

Entity Framework 5 Updating a Record

public interface IRepository
{
    void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class;
}

public class Repository : DbContext, IRepository
{
    public void Update<T>(T obj, params Expression<Func<T, object>>[] propertiesToUpdate) where T : class
    {
        Set<T>().Attach(obj);
        propertiesToUpdate.ToList().ForEach(p => Entry(obj).Property(p).IsModified = true);
        SaveChanges();
    }
}

How to verify if a file exists in a batch file?

Type IF /? to get help about if, it clearly explains how to use IF EXIST.

To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one

Finally copying just means calling COPY and calling another bat file can be done like this:

MYOTHERBATFILE.BAT sync.bat myprogram.ini

git replacing LF with CRLF

In a GNU/Linux shell prompt, dos2unix & unix2dos commands allow you to easely convert/format your files coming from MS Windows

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

C#, Looping through dataset and show each record from a dataset column

foreach (DataRow dr in ds.Tables[0].Rows)
{
    //your code here
}

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

Another bug in Java. I seldom find them, only my second in my 10 year career. This is my solution, as others have mentioned. I have nether used System.gc(). But here, in my case, it is absolutely crucial. Weird? YES!

finally
{
    try
    {
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
        System.gc();
    }
    catch (IOException e)
    {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}

How to create relationships in MySQL

If the tables are innodb you can create it like this:

CREATE TABLE accounts(
    account_id INT NOT NULL AUTO_INCREMENT,
    customer_id INT( 4 ) NOT NULL ,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
    PRIMARY KEY ( account_id ), 
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id) 
) ENGINE=INNODB;

You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look here for more info.

Copy table to a different database on a different SQL Server

Generate the scripts?

Generate a script to create the table then generate a script to insert the data.

check-out SP_ Genereate_Inserts for generating the data insert script.

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You can use the start (^) and end ($) of line indicators:

^[0-9]{2}$

Some language also have functions that allows you to match against an entire string, where-as you were using a find function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^ and $ will be redundant.

GitHub - List commits by author

If the author has a GitHub account, just click the author's username from anywhere in the commit history, and the commits you can see will be filtered down to those by that author:

Screenshot showing where to click to filter down commits

You can also click the 'n commits' link below their name on the repo's "contributors" page:

Another screenshot

Alternatively, you can directly append ?author=<theusername> or ?author=<emailaddress> to the URL. For example, https://github.com/jquery/jquery/commits/master?author=dmethvin or https://github.com/jquery/jquery/commits/[email protected] both give me:

Screenshot with only Dave Methvin's commits

For authors without a GitHub account, only filtering by email address will work, and you will need to manually add ?author=<emailaddress> to the URL - the author's name will not be clickable from the commits list.


You can also get the list of commits by a particular author from the command line using

git log --author=[your git name]

Example:

git log --author=Prem