Programs & Examples On #App data

What is the App_Data folder used for in Visual Studio?

From the documentation about ASP.NET Web Project Folder Structure in MSDN:

You can keep your Web project's files in any folder structure that is convenient for your application. To make it easier to work with your application, ASP.NET reserves certain file and folder names that you can use for specific types of content.

App_Data contains application data files including .mdf database files, XML files, and other data store files. The App_Data folder is used by ASP.NET to store an application's local database, such as the database for maintaining membership and role information. For more information, see Introduction to Membership and Understanding Role Management.

Pandas - How to flatten a hierarchical index in columns

Another simple routine.

def flatten_columns(df, sep='.'):
    def _remove_empty(column_name):
        return tuple(element for element in column_name if element)
    def _join(column_name):
        return sep.join(column_name)

    new_columns = [_join(_remove_empty(column)) for column in df.columns.values]
    df.columns = new_columns

Can I add jars to maven 2 build classpath without installing them?

For throw away code only

set scope == system and just make up a groupId, artifactId, and version

<dependency>
    <groupId>org.swinglabs</groupId>
    <artifactId>swingx</artifactId>
    <version>0.9.2</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/swingx-0.9.3.jar</systemPath>
</dependency>

Note: system dependencies are not copied into resulted jar/war
(see How to include system dependencies in war built using maven)

Changing Node.js listening port

I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js

var server = app.listen(8080, function() {
    console.log('Ready on port %d', server.address().port);
});

This will log Ready on port 8080 to your console.

git checkout all the files

Other way which I found useful is:

git checkout <wildcard> 

Example:

git checkout *.html

More generally:

git checkout <branch> <filename/wildcard>

Error Code: 1406. Data too long for column - MySQL

MySQL will truncate any insert value that exceeds the specified column width.

to make this without error try switch your SQL mode to not use STRICT.

Mysql reference manual


EDIT:

To change the mode

This can be done in two ways:

  1. Open your my.ini (Windows) or my.cnf (Unix) file within the MySQL installation directory, and look for the text "sql-mode".

Find:

Code:

# Set the SQL mode to strict 
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Replace with:

Code:

# Set the SQL mode to strict 
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Or

  1. You can run an SQL query within your database management tool, such as phpMyAdmin:

Code:

SET @@global.sql_mode= '';

Python 2.7.10 error "from urllib.request import urlopen" no module named request

Instead of using urllib.request.urlopen() remove request for python 2.

urllib.urlopen() you do not have to request in python 2.x for what you are trying to do. Hope it works for you. This was tested using python 2.7 I was receiving the same error message and this resolved it.

How can I keep a container running on Kubernetes?

There are many different ways for accomplishing this, but one of the most elegant one is:

kubectl run -i --tty --image ubuntu:latest ubuntu-test --restart=Never --rm /bin/sh

Python - Module Not Found

After trying to add the path using:

pip show

on command prompt and using

sys.path.insert(0, "/home/myname/pythonfiles")

and didn't work. Also got SSL error when trying to install the module again using conda this time instead of pip.

I simply copied the module that wasn't found from the path "Mine was in

C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages 

so I copied it to 'C:\Users\user\Anaconda3\Lib\site-packages'

Define a fixed-size list in Java

If you want to use ArrayList or LinkedList, it seems that the answer is no. Although there are some classes in java that you can set them fixed size, like PriorityQueue, ArrayList and LinkedList can't, because there is no constructor for these two to specify capacity.

If you want to stick to ArrayList/LinkedList, one easy solution is to check the size manually each time.

public void fixedAdd(List<Integer> list, int val, int size) {
    list.add(val);
    if(list.size() > size) list.remove(0);
}

LinkedList is better than ArrayList in this situation. Suppose there are many values to be added but the list size is quite samll, there will be many remove operations. The reason is that the cost of removing from ArrayList is O(N), but only O(1) for LinkedList.

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();
});

How to remove newlines from beginning and end of a string?

If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:

Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:

 s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")

Complete Example:

public class RemoveLineBreaks {
    public static void main(String[] args) {
        var s = "\nHello\nWorld\n";
        System.out.println("before: >"+s+"<");
        s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
        System.out.println("after: >"+s+"<");
    }
}

It outputs:

before: >
Hello
World
<
after: >Hello
World<

Git/GitHub can't push to master

Use Mark Longair's answer, but make sure to use the HTTPS link to the repository:

git remote set-url origin https://github.com/my_user_name/my_repo.git

You can use then git push origin master.

Upload files with HTTPWebrequest (multipart/form-data)

There is another working example with some my comments :

        List<MimePart> mimeParts = new List<MimePart>();

        try
        {
            foreach (string key in form.AllKeys)
            {
                StringMimePart part = new StringMimePart();

                part.Headers["Content-Disposition"] = "form-data; name=\"" + key + "\"";
                part.StringData = form[key];

                mimeParts.Add(part);
            }

            int nameIndex = 0;

            foreach (UploadFile file in files)
            {
                StreamMimePart part = new StreamMimePart();

                if (string.IsNullOrEmpty(file.FieldName))
                    file.FieldName = "file" + nameIndex++;

                part.Headers["Content-Disposition"] = "form-data; name=\"" + file.FieldName + "\"; filename=\"" + file.FileName + "\"";
                part.Headers["Content-Type"] = file.ContentType;

                part.SetStream(file.Data);

                mimeParts.Add(part);
            }

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");

            req.ContentType = "multipart/form-data; boundary=" + boundary;
            req.Method = "POST";

            long contentLength = 0;

            byte[] _footer = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");

            foreach (MimePart part in mimeParts)
            {
                contentLength += part.GenerateHeaderFooterData(boundary);
            }

            req.ContentLength = contentLength + _footer.Length;

            byte[] buffer = new byte[8192];
            byte[] afterFile = Encoding.UTF8.GetBytes("\r\n");
            int read;

            using (Stream s = req.GetRequestStream())
            {
                foreach (MimePart part in mimeParts)
                {
                    s.Write(part.Header, 0, part.Header.Length);

                    while ((read = part.Data.Read(buffer, 0, buffer.Length)) > 0)
                        s.Write(buffer, 0, read);

                    part.Data.Dispose();

                    s.Write(afterFile, 0, afterFile.Length);
                }

                s.Write(_footer, 0, _footer.Length);
            }

            return (HttpWebResponse)req.GetResponse();
        }
        catch
        {
            foreach (MimePart part in mimeParts)
                if (part.Data != null)
                    part.Data.Dispose();

            throw;
        }

And there is example of using :

            UploadFile[] files = new UploadFile[] 
            { 
                new UploadFile(@"C:\2.jpg","new_file","image/jpeg") //new_file is id of upload field
            };

            NameValueCollection form = new NameValueCollection();

            form["id_hidden_input"] = "value_hidden_inpu"; //there is additional param (hidden fields on page)


            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(full URL of action);

            // set credentials/cookies etc. 
            req.CookieContainer = hrm.CookieContainer; //hrm is my class. i copied all cookies from last request to current (for auth)
            HttpWebResponse resp = HttpUploadHelper.Upload(req, files, form);

            using (Stream s = resp.GetResponseStream())
            using (StreamReader sr = new StreamReader(s))
            {
                string response = sr.ReadToEnd();
            }
             //profit!

returning a Void object

If you just don't need anything as your type, you can use void. This can be used for implementing functions, or actions. You could then do something like this:

interface Action<T> {
    public T execute();
}

abstract class VoidAction implements Action<Void> {
    public Void execute() {
        executeInternal();
        return null;
    }

    abstract void executeInternal();
}

Or you could omit the abstract class, and do the return null in every action that doesn't require a return value yourself.

You could then use those actions like this:

Given a method

private static <T> T executeAction(Action<T> action) {
    return action.execute();
}

you can call it like

String result = executeAction(new Action<String>() {
    @Override
    public String execute() {
        //code here
        return "Return me!";
    }
});

or, for the void action (note that you're not assigning the result to anything)

executeAction(new VoidAction() {
    @Override
    public void executeInternal() {
        //code here
    }
});

Xcode source automatic formatting

First, Examine XCode Preferences "Indentation" section. You can customize things quite a bit there...

For more fine grained control, refer to the XCode User Defaults document from apple. (May require a developer login to view). For example, I was able to disable the "indent on paste" by entering the following in terminal:

defaults write com.apple.XCODE PBXIndentOnPaste No

to read back your setting:

defaults read com.apple.XCODE PBXIndentOnPaste

The server principal is not able to access the database under the current security context in SQL Server MS 2012

SQL Logins are defined at the server level, and must be mapped to Users in specific databases.

In SSMS object explorer, under the server you want to modify, expand Security > Logins, then double-click the appropriate user which will bring up the "Login Properties" dialog.

Select User Mapping, which will show all databases on the server, with the ones having an existing mapping selected. From here you can select additional databases (and be sure to select which roles in each database that user should belong to), then click OK to add the mappings.

enter image description here

These mappings can become disconnected after a restore or similar operation. In this case, the user may still exist in the database but is not actually mapped to a login. If that happens, you can run the following to restore the login:

USE {database};
ALTER USER {user} WITH login = {login}

You can also delete the DB user and recreate it from the Login Properties dialog, but any role memberships or other settings would need to be recreated.

How do you implement a Stack and a Queue in JavaScript?

Construct a Queue using two Stacks.

O(1) for both enqueue and dequeue operations.

class Queue {
  constructor() {
    this.s1 = []; // in
    this.s2 = []; // out
  }

  enqueue(val) {
    this.s1.push(val);
  }

  dequeue() {
    if (this.s2.length === 0) {
      this._move();
    }

    return this.s2.pop(); // return undefined if empty
  }

  _move() {
    while (this.s1.length) {
      this.s2.push(this.s1.pop());
    }
  }
}

Export database schema into SQL file

Have you tried the Generate Scripts (Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?

How to make a div 100% height of the browser window

You can use vh in this case which is relative to 1% of the height of the viewport...

That means if you want to cover off the height, just simply use 100vh.

Look at the image below I draw for you here:

How to make a div 100% height of the browser window?

Try the snippet I created for you as below:

_x000D_
_x000D_
.left {_x000D_
  height: 100vh;_x000D_
  width: 50%;_x000D_
  background-color: grey;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  height: 100vh;_x000D_
  width: 50%;_x000D_
  background-color: red;_x000D_
  float: right;_x000D_
}
_x000D_
<div class="left"></div>_x000D_
<div class="right"></div>
_x000D_
_x000D_
_x000D_

Code to loop through all records in MS Access

You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm

My own standard loop looks something like this:

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")

'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst 'Unnecessary in this case, but still a good habit
    Do Until rs.EOF = True
        'Perform an edit
        rs.Edit
        rs!VendorYN = True
        rs("VendorYN") = True 'The other way to refer to a field
        rs.Update

        'Save contact name into a variable
        sContactName = rs!FirstName & " " & rs!LastName

        'Move to the next record. Don't ever forget to do this.
        rs.MoveNext
    Loop
Else
    MsgBox "There are no records in the recordset."
End If

MsgBox "Finished looping through records."

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

How do I store an array in localStorage?

Use JSON.stringify() and JSON.parse() as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three|||bars).

How can you determine a point is between two other points on a line segment?

Here's how I did it at school. I forgot why it is not a good idea.

EDIT:

@Darius Bacon: cites a "Beautiful Code" book which contains an explanation why the belowed code is not a good idea.

#!/usr/bin/env python
from __future__ import division

epsilon = 1e-6

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

class LineSegment:
    """
    >>> ls = LineSegment(Point(0,0), Point(2,4))
    >>> Point(1, 2) in ls
    True
    >>> Point(.5, 1) in ls
    True
    >>> Point(.5, 1.1) in ls
    False
    >>> Point(-1, -2) in ls
    False
    >>> Point(.1, 0.20000001) in ls
    True
    >>> Point(.1, 0.2001) in ls
    False
    >>> ls = LineSegment(Point(1, 1), Point(3, 5))
    >>> Point(2, 3) in ls
    True
    >>> Point(1.5, 2) in ls
    True
    >>> Point(0, -1) in ls
    False
    >>> ls = LineSegment(Point(1, 2), Point(1, 10))
    >>> Point(1, 6) in ls
    True
    >>> Point(1, 1) in ls
    False
    >>> Point(2, 6) in ls 
    False
    >>> ls = LineSegment(Point(-1, 10), Point(5, 10))
    >>> Point(3, 10) in ls
    True
    >>> Point(6, 10) in ls
    False
    >>> Point(5, 10) in ls
    True
    >>> Point(3, 11) in ls
    False
    """
    def __init__(self, a, b):
        if a.x > b.x:
            a, b = b, a
        (self.x0, self.y0, self.x1, self.y1) = (a.x, a.y, b.x, b.y)
        self.slope = (self.y1 - self.y0) / (self.x1 - self.x0) if self.x1 != self.x0 else None

    def __contains__(self, c):
        return (self.x0 <= c.x <= self.x1 and
                min(self.y0, self.y1) <= c.y <= max(self.y0, self.y1) and
                (not self.slope or -epsilon < (c.y - self.y(c.x)) < epsilon))

    def y(self, x):        
        return self.slope * (x - self.x0) + self.y0

if __name__ == '__main__':
    import  doctest
    doctest.testmod()

How to install PyQt5 on Windows?

To install the GPL version of PyQt5, run (see PyQt5 Project):

pip3 install pyqt5

This will install the Python wheel for your platform and your version of Python (assuming both are supported).

(The wheel will be automatically downloaded from the Python Package Index.)

The PyQt5 wheel includes the necessary parts of the LGPL version of Qt. There is no need to install Qt yourself.

(The required sip is packaged as a separate wheel and will be downloaded and installed automatically.)


Note:

If you get an error message saying something as

No downloads could be found that satisfy the requirement 

then you are probably using an unsupported version of Python.

Bitbucket fails to authenticate on git pull

You need to reset the password as shown below.

On macOS:

git config --global credential.helper osxkeychain

On Windows 10:

git config --global credential.helper store

After executing this, it prompts you for the user name and password for your repo.

Submit a form using jQuery

this will send a form with preloader :

var a=$('#yourform').serialize();
$.ajax({
    type:'post',
    url:'receiver url',
    data:a,
    beforeSend:function(){
        launchpreloader();
    },
    complete:function(){
        stopPreloader();
    },
    success:function(result){
         alert(result);
    }
});

i'have some trick to make a form data post reformed with random method http://www.jackart4.com/article.html

Laravel Eloquent limit and offset

laravel have own function skip for offset and take for limit. just like below example of laravel query :-

Article::where([['user_id','=',auth()->user()->id]])
                ->where([['title','LIKE',"%".$text_val."%"]])
                ->orderBy('id','DESC')
                ->skip(0)
                ->take(2)
                ->get();

Save a file in json format using Notepad++

In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON.

Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as .JSON file, you have to just select the location of the file.

Thanks, -Sam

Please look at the pic, it will give you a better idea..

How to set or change the default Java (JDK) version on OS X?

Four easy steps using terminal for people who uses the default process.. :)

  1. echo $JAVA_HOME gives you current java home. For eg: /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/

  2. cd /Library/Java/JavaVirtualMachines/ will take you to the folder where u normally install jdks (It might be different for your machines)

  3. ls shows you available folders (normally it will have the version numbers, for eg: jdk1.8.0_191.jdk openjdk-11.0.2.jdk)
  4. export JAVA_HOME='/Library/Java/JavaVirtualMachines/openjdk-11.0.2.jdk/Contents/Home' will change the java home..

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

var isUnique = true;      
for (var i= 0; i< targetItems.length; i++) {
        var itemValue = $(targetItems[i]).val();
        if (targetListValues.indexOf(itemValue) >= 0) {
          isUnique = false;
           break;
        }
      targetListValues.push(itemValue);
        if (!isUnique) {
          //raise any error msg
          return false;
        }
      }

How to use an arraylist as a prepared statement parameter

@JulienD Best way is to break above process into two steps.

Step 1 : Lets say 'rawList' as your list that you want to add as parameters in prepared statement.

Create another list :

ArrayList<String> listWithQuotes = new ArrayList<String>();

for(String element : rawList){
    listWithQuotes.add("'"+element+"'");
}

Step 2 : Make 'listWithQuotes' comma separated.

String finalString = StringUtils.join(listWithQuotes.iterator(),",");

'finalString' will be string parameters with each element as single quoted and comma separated.

How do I read a file line by line in VB Script?

If anyone like me is searching to read only a specific line, example only line 18 here is the code:

filename = "C:\log.log"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

For i = 1 to 17
    f.ReadLine
Next

strLine = f.ReadLine
Wscript.Echo strLine

f.Close

How to horizontally align ul to center of div?

Following is a list of solutions to centering things in CSS horizontally. The snippet includes all of them.

_x000D_
_x000D_
html {_x000D_
  font: 1.25em/1.5 Georgia, Times, serif;_x000D_
}_x000D_
_x000D_
pre {_x000D_
  color: #fff;_x000D_
  background-color: #333;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
blockquote {_x000D_
  max-width: 400px;_x000D_
  background-color: #e0f0d1;_x000D_
}_x000D_
_x000D_
blockquote > p {_x000D_
  font-style: italic;_x000D_
}_x000D_
_x000D_
blockquote > p:first-of-type::before {_x000D_
  content: open-quote;_x000D_
}_x000D_
_x000D_
blockquote > p:last-of-type::after {_x000D_
  content: close-quote;_x000D_
}_x000D_
_x000D_
blockquote > footer::before {_x000D_
  content: "\2014";_x000D_
}_x000D_
_x000D_
.container,_x000D_
blockquote {_x000D_
  position: relative;_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  background-color: tomato;_x000D_
}_x000D_
_x000D_
.container::after,_x000D_
blockquote::after {_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  padding: 2px 10px;_x000D_
  border: 1px dotted #000;_x000D_
  background-color: #fff;_x000D_
}_x000D_
_x000D_
.container::after {_x000D_
  content: ".container-" attr(data-num);_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
blockquote::after {_x000D_
  content: ".quote-" attr(data-num);_x000D_
  z-index: 2;_x000D_
}_x000D_
_x000D_
.container-4 {_x000D_
  margin-bottom: 200px;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 1_x000D_
 */_x000D_
.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 2_x000D_
 */_x000D_
.container-2 {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 3_x000D_
 */_x000D_
.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 4_x000D_
 */_x000D_
.container-4 {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 5_x000D_
 */_x000D_
.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<main>_x000D_
  <h1>CSS: Horizontal Centering</h1>_x000D_
_x000D_
  <h2>Uncentered Example</h2>_x000D_
  <p>This is the scenario: We have a container with an element inside of it that we want to center. I just added a little padding and background colors so both elements are distinquishable.</p>_x000D_
_x000D_
  <div class="container  container-0" data-num="0">_x000D_
    <blockquote class="quote-0" data-num="0">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 1: Using <code>max-width</code> & <code>margin</code> (IE7)</h2>_x000D_
_x000D_
  <p>This method is widely used. The upside here is that only the element which one wants to center needs rules.</p>_x000D_
_x000D_
<pre><code>.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-1" data-num="1">_x000D_
    <blockquote class="quote  quote-1" data-num="1">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 2: Using <code>display: inline-block</code> and <code>text-align</code> (IE8)</h2>_x000D_
_x000D_
  <p>This method utilizes that <code>inline-block</code> elements are treated as text and as such they are affected by the <code>text-align</code> property. This does not rely on a fixed width which is an upside. This is helpful for when you don’t know the number of elements in a container for example.</p>_x000D_
_x000D_
<pre><code>.container-2 {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-2" data-num="2">_x000D_
    <blockquote class="quote  quote-2" data-num="2">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 3: Using <code>display: table</code> and <code>margin</code> (IE8)</h2>_x000D_
_x000D_
  <p>Very similar to the second solution but only requires to apply rules on the element that is to be centered.</p>_x000D_
_x000D_
<pre><code>.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-3" data-num="3">_x000D_
    <blockquote class="quote  quote-3" data-num="3">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 4: Using <code>translate()</code> and <code>position</code> (IE9)</h2>_x000D_
_x000D_
  <p>Don’t use as a general approach for horizontal centering elements. The downside here is that the centered element will be removed from the document flow. Notice the container shrinking to zero height with only the padding keeping it visible. This is what <i>removing an element from the document flow</i> means.</p>_x000D_
_x000D_
  <p>There are however applications for this technique. For example, it works for <b>vertically</b> centering by using <code>top</code> or <code>bottom</code> together with <code>translateY()</code>.</p>_x000D_
_x000D_
<pre><code>.container-4 {_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-4" data-num="4">_x000D_
    <blockquote class="quote  quote-4" data-num="4">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 5: Using Flexible Box Layout Module (IE10+ with vendor prefix)</h2>_x000D_
_x000D_
  <p></p>_x000D_
_x000D_
<pre><code>.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-5" data-num="5">_x000D_
    <blockquote class="quote  quote-5" data-num="5">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
</main>
_x000D_
_x000D_
_x000D_


display: flex

.container {
  display: flex;
  justify-content: center;
}

Notes:


max-width & margin

You can horizontally center a block-level element by assigning a fixed width and setting margin-right and margin-left to auto.

.container ul {
  /* for IE below version 7 use `width` instead of `max-width` */
  max-width: 800px;
  margin-right: auto;
  margin-left: auto;
}

Notes:

  • No container needed
  • Requires (maximum) width of the centered element to be known

IE9+: transform: translatex(-50%) & left: 50%

This is similar to the quirky centering method which uses absolute positioning and negative margins.

.container {
  position: relative;
}

.container ul {
  position: absolute;
  left: 50%;
  transform: translatex(-50%);
}

Notes:

  • The centered element will be removed from document flow. All elements will completely ignore of the centered element.
  • This technique allows vertical centering by using top instead of left and translateY() instead of translateX(). The two can even be combined.
  • Browser support: transform2d

IE8+: display: table & margin

Just like the first solution, you use auto values for right and left margins, but don’t assign a width. If you don’t need to support IE7 and below, this is better suited, although it feels kind of hacky to use the table property value for display.

.container ul {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

IE8+: display: inline-block & text-align

Centering an element just like you would do with regular text is possible as well. Downside: You need to assign values to both a container and the element itself.

.container {
  text-align: center;
}

.container ul {
  display: inline-block;

  /* One most likely needs to realign flow content */
  text-align: initial;
}

Notes:

  • Does not require to specify a (maximum) width
  • Aligns flow content to the center (potentially unwanted side effect)
  • Works kind of well with a dynamic number of menu items (i.e. in cases where you can’t know the width a single item will take up)

What is the difference between UNION and UNION ALL?

One more thing i would like to add-

Union:- Result set is sorted in ascending order.

Union All:- Result set is not sorted. two Query output just gets appended.

Delimiters in MySQL

You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.

Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.

DELIMITER isn't really a MySQL language command, it's a client command.

Example

DELIMITER $$

/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$

/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/ 
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
    
    SELECT COUNT(*) INTO the_count FROM employees where department=the_department;

END$$

/*DELIMITER is set to it's default*/
DELIMITER ;

Android ImageView Zoom-in and Zoom-Out

Just change ACTION_MOVE_EVENT in Chirag Raval Answer to set ZOOM_IN LIMIT

float[] values = new float[9]; matrix.getValues(values);
                //0.37047964 is limit for zoom in
                if(values[Matrix.MSCALE_X]>0.37047964) {
                    matrix.set(savedMatrix);
                    matrix.postScale(scale, scale, mid.x, mid.y);
                    view.setImageMatrix(matrix);
                }else if (scale>1){
                    matrix.set(savedMatrix);
                    matrix.postScale(scale, scale, mid.x, mid.y);
                    view.setImageMatrix(matrix);
                }

Fragment pressing back button

Still better solution could be to follow a design pattern such that the back-button press event gets propagated from active fragment down to host Activity. So, it's like.. if one of the active fragments consume the back-press, the Activity wouldn't get to act upon it, and vice-versa.

One way to do it is to have all your Fragments extend a base fragment that has an abstract 'boolean onBackPressed()' method.

@Override
public boolean onBackPressed() {
   if(some_condition)
      // Do something
      return true; //Back press consumed.
   } else {
      // Back-press not consumed. Let Activity handle it
      return false;
   }
}

Keep track of active fragment inside your Activity and inside it's onBackPressed callback write something like this

@Override
public void onBackPressed() {
   if(!activeFragment.onBackPressed())
      super.onBackPressed();
   }
}

This post has this pattern described in detail

Bootstrap 4: responsive sidebar menu to top navbar

Big screen:

navigation side bar in big screen size

Small screen (Mobile)

sidebar in small mobile size screen

if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview

CSS + HTML + JQUERY :

_x000D_
_x000D_
    _x000D_
    @import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
    body {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      background: #fafafa;_x000D_
    }_x000D_
    _x000D_
    p {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      font-size: 1.1em;_x000D_
      font-weight: 300;_x000D_
      line-height: 1.7em;_x000D_
      color: #999;_x000D_
    }_x000D_
    _x000D_
    a,_x000D_
    a:hover,_x000D_
    a:focus {_x000D_
      color: inherit;_x000D_
      text-decoration: none;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    .navbar {_x000D_
      padding: 15px 10px;_x000D_
      background: #fff;_x000D_
      border: none;_x000D_
      border-radius: 0;_x000D_
      margin-bottom: 40px;_x000D_
      box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
    }_x000D_
    _x000D_
    .navbar-btn {_x000D_
      box-shadow: none;_x000D_
      outline: none !important;_x000D_
      border: none;_x000D_
    }_x000D_
    _x000D_
    .line {_x000D_
      width: 100%;_x000D_
      height: 1px;_x000D_
      border-bottom: 1px dashed #ddd;_x000D_
      margin: 40px 0;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #sidebar {_x000D_
      width: 250px;_x000D_
      position: fixed;_x000D_
      top: 0;_x000D_
      left: 0;_x000D_
      height: 100vh;_x000D_
      z-index: 999;_x000D_
      background: #7386D5;_x000D_
      color: #fff !important;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    #sidebar.active {_x000D_
      margin-left: -250px;_x000D_
    }_x000D_
    _x000D_
    #sidebar .sidebar-header {_x000D_
      padding: 20px;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul.components {_x000D_
      padding: 20px 0;_x000D_
      border-bottom: 1px solid #47748b;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul p {_x000D_
      color: #fff;_x000D_
      padding: 10px;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a {_x000D_
      padding: 10px;_x000D_
      font-size: 1.1em;_x000D_
      display: block;_x000D_
      color:white;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a:hover {_x000D_
      color: #7386D5;_x000D_
      background: #fff;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li.active>a,_x000D_
    a[aria-expanded="true"] {_x000D_
      color: #fff;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    a[data-toggle="collapse"] {_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="false"]::before,_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e259';_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      right: 20px;_x000D_
      font-family: 'Glyphicons Halflings';_x000D_
      font-size: 0.6em;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e260';_x000D_
    }_x000D_
    _x000D_
    ul ul a {_x000D_
      font-size: 0.9em !important;_x000D_
      padding-left: 30px !important;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs {_x000D_
      padding: 20px;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs a {_x000D_
      text-align: center;_x000D_
      font-size: 0.9em !important;_x000D_
      display: block;_x000D_
      border-radius: 5px;_x000D_
      margin-bottom: 5px;_x000D_
    }_x000D_
    _x000D_
    a.download {_x000D_
      background: #fff;_x000D_
      color: #7386D5;_x000D_
    }_x000D_
    _x000D_
    a.article,_x000D_
    a.article:hover {_x000D_
      background: #6d7fcc !important;_x000D_
      color: #fff !important;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #content {_x000D_
      width: calc(100% - 250px);_x000D_
      padding: 40px;_x000D_
      min-height: 100vh;_x000D_
      transition: all 0.3s;_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      right: 0;_x000D_
    }_x000D_
    _x000D_
    #content.active {_x000D_
      width: 100%;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    @media (max-width: 768px) {_x000D_
      #sidebar {_x000D_
        margin-left: -250px;_x000D_
      }_x000D_
      #sidebar.active {_x000D_
        margin-left: 0;_x000D_
      }_x000D_
      #content {_x000D_
        width: 100%;_x000D_
      }_x000D_
      #content.active {_x000D_
        width: calc(100% - 250px);_x000D_
      }_x000D_
      #sidebarCollapse span {_x000D_
        display: none;_x000D_
      }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
  <title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
  <!-- Bootstrap CSS CDN -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Our Custom CSS -->_x000D_
  <link rel="stylesheet" href="style2.css">_x000D_
  <!-- Scrollbar Custom CSS -->_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
  <div class="wrapper">_x000D_
    <!-- Sidebar Holder -->_x000D_
    <nav id="sidebar">_x000D_
      <div class="sidebar-header">_x000D_
        <h3>Header as you want </h3>_x000D_
        </h3>_x000D_
      </div>_x000D_
_x000D_
      <ul class="list-unstyled components">_x000D_
        <p>Dummy Heading</p>_x000D_
        <li class="active">_x000D_
          <a href="#menu">Animación</a>_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Interacción</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Blog</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Acerca</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">contacto</a>_x000D_
        </li>_x000D_
_x000D_
_x000D_
      </ul>_x000D_
_x000D_
_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content Holder -->_x000D_
    <div id="content">_x000D_
_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container-fluid">_x000D_
_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
                                <i class="glyphicon glyphicon-align-left"></i>_x000D_
                                <span>Toggle Sidebar</span>_x000D_
                            </button>_x000D_
          </div>_x000D_
_x000D_
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="#">Page</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
  <!-- jQuery CDN -->_x000D_
  <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
  <!-- Bootstrap Js CDN -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <!-- jQuery Custom Scroller CDN -->_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
_x000D_
_x000D_
      $('#sidebarCollapse').on('click', function() {_x000D_
        $('#sidebar, #content').toggleClass('active');_x000D_
        $('.collapse.in').toggleClass('in');_x000D_
        $('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
      });_x000D_
    });_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

if this is what you want .

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

try this method

$("your id or class name").css({ 'margin-top': '18px' });  

How can I shuffle an array?

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

Copy an entire worksheet to a new worksheet in Excel 2010

If anyone has, like I do, an Estimating workbook with a default number of visible pricing sheets, a Summary and a larger number of hidden and 'protected' worksheets full of sensitive data but may need to create additional visible worksheets to arrive at a proper price, I have variant of the above responses that creates the said visible worksheets based on a protected hidden "Master". I have used the code provided by @/jean-fran%c3%a7ois-corbett and @thanos-a in combination with simple VBA as shown below.

Sub sbInsertWorksheetAfter()

    'This adds a new visible worksheet after the last visible worksheet

    ThisWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)

    'This copies the content of the HIDDEN "Master" worksheet to the new VISIBLE ActiveSheet just created

    ThisWorkbook.Sheets("Master").Cells.Copy _
        Destination:=ActiveSheet.Cells

    'This gives the the new ActiveSheet a default name

    With ActiveSheet
        .Name = Sheet12.Name & " copied"
    End With

    'This changes the name of the ActiveSheet to the user's preference

    Dim sheetname As String

    With ActiveSheet
        sheetname = InputBox("Enter name of this Worksheet")
        .Name = sheetname
    End With

End Sub

Check if number is decimal

is_numeric returns true for decimals and integers. So if your user lazily enters 1 instead of 1.00 it will still return true:

echo is_numeric(1); // true
echo is_numeric(1.00); // true

You may wish to convert the integer to a decimal with PHP, or let your database do it for you.

Is there a command line command for verifying what version of .NET is installed

Unfortunately the best way would be to check for that directory. I am not sure what you mean but "actually installed" as .NET 3.5 uses the same CLR as .NET 3.0 and .NET 2.0 so all new functionality is wrapped up in new assemblies that live in that directory. Basically, if the directory is there then 3.5 is installed.

Only thing I would add is to find the dir this way for maximum flexibility:

%windir%\Microsoft.NET\Framework\v3.5

How do I apply a diff patch on Windows?

The patch tells it what file to apply to. The header should be something like (view it in Notepad or your fav text editor):

--- Folder/old_file
+++ Folder/new_file

In the case of a Subversion patch, you'd have revision numbers as well (since the file names are the same).

GNU patch will let you override those names, but I don't know of any GUI tools to do the same. I'd check with the various diff programs - though, it does not appear WinMerge supports applying patches.

Apache redirect to another port

This might be an old question, but here's what I did:

In a .conf file loaded by apache:

<VirtualHost *:80>
  ServerName something.com
  ProxyPass / http://localhost:8080/
</VirtualHost>

Explanation: Listen on all requests to the local machine's port 80. If I requested "http://something.com/somethingorother", forward that request to "http://localhost:8080/somethingorother". This should work for an external visitor because, according to the docs, it maps the remote request to the local server's space.

I'm running Apache 2.4.6-2ubuntu2.2, so I'm not sure how the "-2ubuntu2.2" affects the wider applicability of this answer.

After you make these changes, add the needed modules and restart apache

sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart

Get all column names of a DataTable into string array using (LINQ/Predicate)

I'd suggest using such extension method:

public static class DataColumnCollectionExtensions
{
    public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
    {
        return source.Cast<DataColumn>();
    }
}

And therefore:

string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();

You may also implement one more extension method for DataTable class to reduce code:

public static class DataTableExtensions
{
    public static IEnumerable<DataColumn> GetColumns(this DataTable source)
    {
        return source.Columns.AsEnumerable();
    }
}

And use it as follows:

string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();

Vue.js dynamic images not working

I encountered the same problem. This worked for me by changing '../assets/' to './assets/'.

 <img v-bind:src="'./assets/' + pic + '.png'" v-bind:alt="pic">

How do I list all files of a directory?

Returning a list of absolute filepaths, does not recurse into subdirectories

L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))]

Python function attributes - uses and abuses

Sometimes I use an attribute of a function for caching already computed values. You can also have a generic decorator that generalizes this approach. Be aware of concurrency issues and side effects of such functions!

curl -GET and -X GET

The use of -X [WHATEVER] merely changes the request's method string used in the HTTP request. This is easier to understand with two examples — one with -X [WHATEVER] and one without — and the associated HTTP request headers for each:

# curl -XPANTS -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.224.86.126) port 80 (#0)
> PANTS / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*

# curl -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.33.50.167) port 80 (#0)
> GET / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*

How to check the maximum number of allowed connections to an Oracle database?

select count(*),sum(decode(status, 'ACTIVE',1,0)) from v$session where type= 'USER'

Regular Expression to select everything before and up to a particular text

After executing the below regex, your answer is in the first capture.

/^(.*?)\.txt/

How do include paths work in Visual Studio?

This answer will be useful for those who use a non-standard IDE (i.e. Qt Creator).

There are at least two non-intrusive ways to pass additional include paths to Visual Studio's cl.exe via environment variables:

  • Set INCLUDE environment variable to ;-separated list of all include paths. It overrides all includes, inclusive standard library ones. Not recommended.
  • Set CL environment variable to the following value: /I C:\Lib\VulkanMemoryAllocator\src /I C:\Lib\gli /I C:\Lib\gli\external, where each argument of /I key is additional include path.

I successfully use the last one.

SQL injection that gets around mysql_real_escape_string()

The short answer is yes, yes there is a way to get around mysql_real_escape_string(). #For Very OBSCURE EDGE CASES!!!

The long answer isn't so easy. It's based off an attack demonstrated here.

The Attack

So, let's start off by showing the attack...

mysql_query('SET NAMES gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

In certain circumstances, that will return more than 1 row. Let's dissect what's going on here:

  1. Selecting a Character Set

    mysql_query('SET NAMES gbk');
    

    For this attack to work, we need the encoding that the server's expecting on the connection both to encode ' as in ASCII i.e. 0x27 and to have some character whose final byte is an ASCII \ i.e. 0x5c. As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5, cp932, gb2312, gbk and sjis. We'll select gbk here.

    Now, it's very important to note the use of SET NAMES here. This sets the character set ON THE SERVER. If we used the call to the C API function mysql_set_charset(), we'd be fine (on MySQL releases since 2006). But more on why in a minute...

  2. The Payload

    The payload we're going to use for this injection starts with the byte sequence 0xbf27. In gbk, that's an invalid multibyte character; in latin1, it's the string ¿'. Note that in latin1 and gbk, 0x27 on its own is a literal ' character.

    We have chosen this payload because, if we called addslashes() on it, we'd insert an ASCII \ i.e. 0x5c, before the ' character. So we'd wind up with 0xbf5c27, which in gbk is a two character sequence: 0xbf5c followed by 0x27. Or in other words, a valid character followed by an unescaped '. But we're not using addslashes(). So on to the next step...

  3. mysql_real_escape_string()

    The C API call to mysql_real_escape_string() differs from addslashes() in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1 for the connection, because we never told it otherwise. We did tell the server we're using gbk, but the client still thinks it's latin1.

    Therefore the call to mysql_real_escape_string() inserts the backslash, and we have a free hanging ' character in our "escaped" content! In fact, if we were to look at $var in the gbk character set, we'd see:

    ?' OR 1=1 /*

    Which is exactly what the attack requires.

  4. The Query

    This part is just a formality, but here's the rendered query:

    SELECT * FROM test WHERE name = '?' OR 1=1 /*' LIMIT 1
    

Congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

It gets worse. PDO defaults to emulating prepared statements with MySQL. That means that on the client side, it basically does a sprintf through mysql_real_escape_string() (in the C library), which means the following will result in a successful injection:

$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Now, it's worth noting that you can prevent this by disabling emulated prepared statements:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version).

The Ugly

I said at the very beginning that we could have prevented all of this if we had used mysql_set_charset('gbk') instead of SET NAMES gbk. And that's true provided you are using a MySQL release since 2006.

If you're using an earlier MySQL release, then a bug in mysql_real_escape_string() meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20, 5.0.22 and 5.1.11.

But the worst part is that PDO didn't expose the C API for mysql_set_charset() until 5.3.6, so in prior versions it cannot prevent this attack for every possible command! It's now exposed as a DSN parameter.

The Saving Grace

As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4 is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8, which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane.

Alternatively, you can enable the NO_BACKSLASH_ESCAPES SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string(). With this mode enabled, 0x27 will be replaced with 0x2727 rather than 0x5c27 and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27 is still 0xbf27 etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode.

Safe Examples

The following examples are safe:

mysql_query('SET NAMES utf8');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because the server's expecting utf8...

mysql_set_charset('gbk');
$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

Because we've properly set the character set so the client and the server match.

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES gbk');
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've turned off emulated prepared statements.

$pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(array("\xbf\x27 OR 1=1 /*"));

Because we've set the character set properly.

$mysqli->query('SET NAMES gbk');
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "\xbf\x27 OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

Because MySQLi does true prepared statements all the time.

Wrapping Up

If you:

  • Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) AND mysql_set_charset() / $mysqli->set_charset() / PDO's DSN charset parameter (in PHP = 5.3.6)

OR

  • Don't use a vulnerable character set for connection encoding (you only use utf8 / latin1 / ascii / etc)

You're 100% safe.

Otherwise, you're vulnerable even though you're using mysql_real_escape_string()...

How to read a single character at a time from a file in Python?

Just:

myfile = open(filename)
onecaracter = myfile.read(1)

Connect to SQL Server database from Node.js

msnodesql is working out great for me. Here is a sample:

var mssql = require('msnodesql'), 
    express = require('express'),
    app = express(),
    nconf = require('nconf')

nconf.env()
     .file({ file: 'config.json' });

var conn = nconf.get("SQL_CONN");   
var conn_str = "Driver={SQL Server Native Client 11.0};Server=server.name.here;Database=Product;Trusted_Connection={Yes}";

app.get('/api/brands', function(req, res){
    var data = [];
    var jsonObject = {};    

    mssql.open(conn_str, function (err, conn) {
        if (err) {
            console.log("Error opening the connection!");
            return;
        }
        conn.queryRaw("dbo.storedproc", function (err, results) {
        if(err) {
                   console.log(err);
                   res.send(500, "Cannot retrieve records.");
                }
       else {
             //res.json(results);

             for (var i = 0; i < results.rows.length; i++) {
                 var jsonObject = new Object()
                 for (var j = 0; j < results.meta.length; j++) { 

                    paramName = results.meta[j].name;
                    paramValue = results.rows[i][j]; 
                    jsonObject[paramName] = paramValue;

                    }
                    data.push(jsonObject);  //This is a js object we are jsonizing not real json until res.send             
            } 

                res.send(data);

            }       
        });
    });
});

How to set default vim colorscheme

OS: Redhat enterprise edition

colo schema_name works fine if you are facing problems with colorscheme.

Is there a short cut for going back to the beginning of a file by vi editor?

I've always used Ctrl + Home (start of file) and Ctrl + End (end of file).

Works in both insert and nav modes.

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

OK, just change your code to something like this:

<script>
function submit() {
   return confirm('Do you really want to submit the form?');
}
</script>

<form onsubmit="return submit(this);">
   <input type="image" src="xxx" border="0" name="submit" onclick="show_alert();"
      alt="PayPal - The safer, easier way to pay online!" value="Submit">
</form>

Also this is the code in run, just I make it easier to see how it works, just run the code below to see the result:

_x000D_
_x000D_
function submitForm() {_x000D_
  return confirm('Do you really want to submit the form?');_x000D_
}
_x000D_
<form onsubmit="return submitForm(this);">_x000D_
  <input type="text" border="0" name="submit" />_x000D_
  <button value="submit">submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How can I copy a Python string?

You can copy a string in python via string formatting :

>>> a = 'foo'  
>>> b = '%s' % a  
>>> id(a), id(b)  
(140595444686784, 140595444726400)  

What is the best way to extract the first word from a string in Java?

The simple one I used to do is

str.contains(" ") ? str.split(" ")[0] : str

Where str is your string or text bla bla :). So, if

  1. str is having empty value it returns as it is.
  2. str is having one word, it returns as it is.
  3. str is multiple words, it extract the first word and return.

Hope this is helpful.

What is the command to truncate a SQL Server log file?

backup log logname with truncate_only followed by a dbcc shrinkfile command

PHP Remove elements from associative array

for single array Item use reset($item)

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

Zoom to fit all markers in Mapbox or Leaflet

The best way is to use the next code

var group = new L.featureGroup([marker1, marker2, marker3]);

map.fitBounds(group.getBounds());

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

How can I put a ListView into a ScrollView without it collapsing?

There's a built-in setting for it. On the ScrollView:

android:fillViewport="true"

In Java,

mScrollView.setFillViewport(true);

Romain Guy explains it in depth here: http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/

What is a Sticky Broadcast?

If an Activity calls onPause with a normal broadcast, receiving the Broadcast can be missed. A sticky broadcast can be checked after it was initiated in onResume.

Update 6/23/2020

Sticky broadcasts are deprecated.

See sendStickyBroadcast documentation.

This method was deprecated in API level 21.

Sticky broadcasts should not be used. They provide no security (anyone can access them), no protection (anyone can modify them), and many other problems. The recommended pattern is to use a non-sticky broadcast to report that something has changed, with another mechanism for apps to retrieve the current value whenever desired.

Implement

Intent intent = new Intent("some.custom.action");
intent.putExtra("some_boolean", true);
sendStickyBroadcast(intent);

Resources

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

Float a div above page content

You want to use absolute positioning.

An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is html

For instance :

.yourDiv{
  position:absolute;
  top: 123px;
}

To get it to work, the parent needs to be relative (position:relative)

In your case this should do the trick:

.suggestionsBox{position:absolute; top:40px;}
#specific_locations_add{position:relative;}

jquery's append not working with svg element?

JQuery can't append elements to <svg> (it does seem to add them in the DOM explorer, but not on the screen).

One workaround is to append an <svg> with all of the elements that you need to the page, and then modify the attributes of the elements using .attr().

$('body')
  .append($('<svg><circle id="c" cx="10" cy="10" r="10" fill="green" /></svg>'))
  .mousemove( function (e) {
      $("#c").attr({
          cx: e.pageX,
          cy: e.pageY
      });
  });

http://jsfiddle.net/8FBjb/1/

How to Use UTF-8 Collation in SQL Server database?

No! It's not a joke.

Take a look here: http://msdn.microsoft.com/en-us/library/ms186939.aspx

Character data types that are either fixed-length, nchar, or variable-length, nvarchar, Unicode data and use the UNICODE UCS-2 character set.

And also here: http://en.wikipedia.org/wiki/UTF-16

The older UCS-2 (2-byte Universal Character Set) is a similar character encoding that was superseded by UTF-16 in version 2.0 of the Unicode standard in July 1996.

How to remove element from array in forEach loop?

Use Array.prototype.filter instead of forEach:

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'b', 'c', 'b', 'a', 'e'];
review = review.filter(item => item !== 'a');
log(review);

How can I use delay() with show() and hide() in Jquery

Pass a duration to show() and hide():

When a duration is provided, .show() becomes an animation method.

E.g. element.delay(1000).show(0)

DEMO

How do browser cookie domains work?

The last (third to be exactly) RFC for this issue is RFC-6265 (Obsoletes RFC-2965 that in turn obsoletes RFC-2109).

According to it if the server omits the Domain attribute, the user agent will return the cookie only to the origin server (the server on which a given resource resides). But it's also warning that some existing user agents treat an absent Domain attribute as if the Domain attribute were present and contained the current host name (For example, if example.com returns a Set-Cookie header without a Domain attribute, these user agents will erroneously send the cookie to www.example.com as well).

When the Domain attribute have been specified, it will be treated as complete domain name (if there is the leading dot in attribute it will be ignored). Server should match the domain specified in attribute (have exactly the same domain name or to be a subdomain of it) to get this cookie. More accurately it specified here.

So, for example:

  • cookie attribute Domain=.example.com is equivalent to Domain=example.com
  • cookies with such Domain attributes will be available for example.com and www.example.com
  • cookies with such Domain attributes will be not available for another-example.com
  • specifying cookie attribute like Domain=www.example.com will close the way for www4.example.com

PS: trailing comma in Domain attribute will cause the user agent to ignore the attribute =(

How do I address unchecked cast warnings?

Just typecheck it before you cast it.

Object someObject = session.getAttribute("attributeKey");
if(someObject instanceof HashMap)
HashMap<String, String> theHash = (HashMap<String, String>)someObject;  

And for anyone asking, it's quite common to receive objects where you aren't sure of the type. Plenty of legacy "SOA" implementations pass around various objects that you shouldn't always trust. (The horrors!)

EDIT Changed the example code once to match the poster's updates, and following some comments I see that instanceof doesn't play nicely with generics. However changing the check to validate the outer object seems to play well with the commandline compiler. Revised example now posted.

pass JSON to HTTP POST Request

       var request = require('request');
        request({
            url: "http://localhost:8001/xyz",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(requestData)
        }, function(error, response, body) {
            console.log(response);
        });

Adding sheets to end of workbook in Excel (normal method not working?)

A common mistake is

mainWB.Sheets.Add(After:=Sheets.Count)

which leads to Error 1004. Although it is not clear at all from the official documentation, it turns out that the 'After' parameter cannot be an integer, it must be a reference to a sheet in the same workbook.

How to hide first section header in UITableView (grouped style)

Use this trick for grouped type tableView

Copy paste below code for your table view in viewDidLoad method:

tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, tableView.bounds.size.width, 0.01f)];

Insert a line break in mailto body

For plaintext email using JavaScript, you may also use \r with encodeURIComponent().

For example, this message:

hello\rthis answer is now well formated\rand it contains good knowleadge\rthat is why I am up voting

URI Encoded, results in:

hello%0Dthis%20answer%20is%20now%20well%20formated%0Dand%20it%20contains%20good%20knowleadge%0Dthat%20is%20why%20I%20am%20up%20voting

And, using the href:

mailto:[email protected]?body=hello%0Dthis%20answer%20is%20now%20well%20formated%0Dand%20it%20contains%20good%20knowleadge%0Dthat%20is%20why%20I%20am%20up%20voting

Will result in the following email body text:

hello
this answer is now well formated
and it contains good knowleadge
that is why I am up voting

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

What is Common Gateway Interface (CGI)?

You maybe want to know what is not CGI, and the answer is a MODULE for your web server (if I suppose you are runnig Apache). AND THAT'S THE BIG DIFERENCE, because CGI needs and external program, thread, whatever to instantiate a PERL, PHP, C app server where when you run as a MODULE that program is the web server (apache) per-se.

Because of all this there is a lot of performance, security, portability issues that come into play. But it's good to know what is not CGI first, to understand what it is.

How to set text size in a button in html

Without using inline CSS you could set the text size of all your buttons using:

input[type="submit"], input[type="button"] {
  font-size: 14px;
}

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

How should I import data from CSV into a Postgres table using pgAdmin 3?

assuming you have a SQL table called mydata - you can load data from a csv file as follows:

COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;

For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html

Python Loop: List Index Out of Range

Try reducing the range of the for loop to range(len(a)-1):

a = [0,1,2,3]
b = []

for i in range(len(a)-1):
    b.append(a[i]+a[i+1])

print(b)

This can also be written as a list comprehension:

b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)

How do I add a Fragment to an Activity with a programmatically created content view

Here is what I came up with after reading Tony Wong's comment:

public class DebugExampleTwo extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addFragment(android.R.id.content,
                    new DebugExampleTwoFragment(),
                    DebugExampleTwoFragment.FRAGMENT_TAG);
    }

}

...

public abstract class BaseActivity extends Activity {

    protected void addFragment(@IdRes int containerViewId,
                               @NonNull Fragment fragment,
                               @NonNull String fragmentTag) {
        getSupportFragmentManager()
                .beginTransaction()
                .add(containerViewId, fragment, fragmentTag)
                .disallowAddToBackStack()
                .commit();
    }

    protected void replaceFragment(@IdRes int containerViewId,
                                   @NonNull Fragment fragment,
                                   @NonNull String fragmentTag,
                                   @Nullable String backStackStateName) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(containerViewId, fragment, fragmentTag)
                .addToBackStack(backStackStateName)
                .commit();
    }

}

...

public class DebugExampleTwoFragment extends Fragment {

    public static final String FRAGMENT_TAG = 
        BuildConfig.APPLICATION_ID + ".DEBUG_EXAMPLE_TWO_FRAGMENT_TAG";

    // ...

}

Kotlin

If you are using Kotlin make sure to take a look at what the Kotlin extensions by Google provide or just write your own.

How to implement 2D vector array?

I use this piece of code . works fine for me .copy it and run on your computer. you'll understand by yourself .

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector <vector <int> > matrix;
    size_t row=3 , col=3 ;
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            vector <int> colVector ;
            matrix.push_back(colVector) ;
            matrix.at(i).push_back(cnt++) ;
        }
    }
    matrix.at(1).at(1) = 0;     //matrix.at(columns).at(rows) = intValue 
    //printing all elements
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            cout<<matrix[i][j] <<" " ;
        }
        cout<<endl ;
    }
}

Force browser to clear cache

If you are a Wordpress developer I have some great news for you.

Just search for, install and activate the Wordpress plugin called: reBusted.

No configuration is necessary.

It will automatically force cache refresh if the content has been updated and it solves this issue completely and reliably. Tested and used on hundreds of clients Wordpress sites – works perfectly everywhere.

Cannot recommend it enough.

If you use Wordpress, this is by far your best option and most elegant resolution for this issue.

Enjoy!

How to center a <p> element inside a <div> container?

Centered and middled content ?

Do it this way :

<table style="width:100%">
    <tr>
        <td valign="middle" align="center">Table once ruled centering</td>
    </tr>
</table>

I fiddled it here

Ha, let me guess .. you want DIVs ..

just make your first outter DIV behave like a table-cell then style it with vertical align:middle;

<div>
    <p>I want this paragraph to be at the center, but I can't.</p>
</div>

div {
    width:500px;
    height:100px;
    background-color:aqua;
    text-align:center;
    /*  there it is */
    display:table-cell;
    vertical-align:middle;
}

jsfiddle.net/9Mk64/

Viewing all defined variables

If possible, you may want to use IPython.

To get a list of all current user-defined variables, IPython provides a magic command named who (magics must be prefixed with the modulo character unless the automagic feature is enabled):

In [1]: foo = 'bar'
In [2]: %who
foo

You can use the whos magic to get more detail:

In [3]: %whos
Variable   Type    Data/Info
----------------------------
foo        str     bar

There are a wealth of other magics available. IPython is basically the Python interpreter on steroids. One convenient magic is store, which lets you save variables between sessions (using pickle).

Note: I am not associated with IPython Dev - just a satisfied user.

Edit:

You can find all the magic commands in the IPython Documentation.

This article also has a helpful section on the use of magic commands in Jupyter Notebook

How to stop the task scheduled in java.util.Timer class

timer.cancel();  //Terminates this timer,discarding any currently scheduled tasks.

timer.purge();   // Removes all cancelled tasks from this timer's task queue.

How to do a Jquery Callback after form submit?

I do not believe there is a callback-function like the one you describe.

What is normal here is to do the alterations using some server-side language, like PHP.

In PHP you could for instance fetch a hidden field from your form and do some changes if it is present.

PHP:

  $someHiddenVar = $_POST["hidden_field"];
    if (!empty($someHiddenVar)) {
        // do something 
    }

One way to go about it in Jquery is to use Ajax. You could listen to submit, return false to cancel its default behaviour and use jQuery.post() instead. jQuery.post has a success-callback.

$.post("test.php", $("#testform").serialize(), function(data) {
  $('.result').html(data);
});

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

How do I create a new branch?

In the Repository Browser of TortoiseSVN, find the branch that you want to create the new branch from. Right-click, Copy To.... and enter the new branch path. Now you can "switch" your local WC to that branch.

Select Pandas rows based on list index

Another way (although it is a longer code) but it is faster than the above codes. Check it using %timeit function:

df[df.index.isin([1,3])]

PS: You figure out the reason

enter image description here

Bootstrap 3 - Responsive mp4-video

using that code wil give you a responsive video player with full control

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" width="640" height="480" src="https://www.youtube-nocookie.com/embed/Lw_e0vF1IB4" frameborder="0" allowfullscreen></iframe>
</div>

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

How to convert numbers between hexadecimal and decimal

This is not really easiest way but this source code enable you to right any types of octal number i.e 23.214, 23 and 0.512 and so on. Hope this will help you..

    public string octal_to_decimal(string m_value)
    {
        double i, j, x = 0;
        Int64 main_value;
        int k = 0;
        bool pw = true, ch;
        int position_pt = m_value.IndexOf(".");
        if (position_pt == -1)
        {
            main_value = Convert.ToInt64(m_value);
            ch = false;
        }
        else
        {
            main_value = Convert.ToInt64(m_value.Remove(position_pt, m_value.Length - position_pt));
            ch = true;
        }

        while (k <= 1)
        {
            do
            {
                i = main_value % 10;                                        // Return Remainder
                i = i * Convert.ToDouble(Math.Pow(8, x));                   // calculate power
                if (pw)
                    x++;
                else
                    x--;
                o_to_d = o_to_d + i;                                        // Saving Required calculated value in main variable
                main_value = main_value / 10;                               // Dividing the main value 
            }
            while (main_value >= 1);
            if (ch)
            {
                k++;
                main_value = Convert.ToInt64(Reversestring(m_value.Remove(0, position_pt + 1)));
            }
            else
                k = 2;
            pw = false;
            x = -1;
        }
        return (Convert.ToString(o_to_d));
    }    

Insert line break in wrapped cell via code

Yes. The VBA equivalent of AltEnter is to use a linebreak character:

ActiveCell.Value = "I am a " & Chr(10) & "test"

Note that this automatically sets WrapText to True.

Proof:

Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub

Modify request parameter with servlet filter

Based on all your remarks here is my proposal that worked for me :

 private final class CustomHttpServletRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> queryParameterMap;
    private final Charset requestEncoding;

    public CustomHttpServletRequest(HttpServletRequest request) {
        super(request);
        queryParameterMap = getCommonQueryParamFromLegacy(request.getParameterMap());

        String encoding = request.getCharacterEncoding();
        requestEncoding = (encoding != null ? Charset.forName(encoding) : StandardCharsets.UTF_8);
    }

    private final Map<String, String[]> getCommonQueryParamFromLegacy(Map<String, String[]> paramMap) {
        Objects.requireNonNull(paramMap);

        Map<String, String[]> commonQueryParamMap = new LinkedHashMap<>(paramMap);

        commonQueryParamMap.put(CommonQueryParams.PATIENT_ID, new String[] { paramMap.get(LEGACY_PARAM_PATIENT_ID)[0] });
        commonQueryParamMap.put(CommonQueryParams.PATIENT_BIRTHDATE, new String[] { paramMap.get(LEGACY_PARAM_PATIENT_BIRTHDATE)[0] });
        commonQueryParamMap.put(CommonQueryParams.KEYWORDS, new String[] { paramMap.get(LEGACY_PARAM_STUDYTYPE)[0] });

        String lowerDateTime = null;
        String upperDateTime = null;

        try {
            String studyDateTime = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("dd-MM-yyyy").parse(paramMap.get(LEGACY_PARAM_STUDY_DATE_TIME)[0]));

            lowerDateTime = studyDateTime + "T23:59:59";
            upperDateTime = studyDateTime + "T00:00:00";

        } catch (ParseException e) {
            LOGGER.error("Can't parse StudyDate from query parameters : {}", e.getLocalizedMessage());
        }

        commonQueryParamMap.put(CommonQueryParams.LOWER_DATETIME, new String[] { lowerDateTime });
        commonQueryParamMap.put(CommonQueryParams.UPPER_DATETIME, new String[] { upperDateTime });

        legacyQueryParams.forEach(commonQueryParamMap::remove);
        return Collections.unmodifiableMap(commonQueryParamMap);

    }

    @Override
    public String getParameter(String name) {
        String[] params = queryParameterMap.get(name);
        return params != null ? params[0] : null;
    }

    @Override
    public String[] getParameterValues(String name) {
        return queryParameterMap.get(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
            return queryParameterMap; // unmodifiable to uphold the interface contract.
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return Collections.enumeration(queryParameterMap.keySet());
        }

        @Override
        public String getQueryString() {
            // @see : https://stackoverflow.com/a/35831692/9869013
            // return queryParameterMap.entrySet().stream().flatMap(entry -> Stream.of(entry.getValue()).map(value -> entry.getKey() + "=" + value)).collect(Collectors.joining("&")); // without encoding !!
            return queryParameterMap.entrySet().stream().flatMap(entry -> encodeMultiParameter(entry.getKey(), entry.getValue(), requestEncoding)).collect(Collectors.joining("&"));
        }

        private Stream<String> encodeMultiParameter(String key, String[] values, Charset encoding) {
            return Stream.of(values).map(value -> encodeSingleParameter(key, value, encoding));
        }

        private String encodeSingleParameter(String key, String value, Charset encoding) {
            return urlEncode(key, encoding) + "=" + urlEncode(value, encoding);
        }

        private String urlEncode(String value, Charset encoding) {
            try {
                return URLEncoder.encode(value, encoding.name());
            } catch (UnsupportedEncodingException e) {
                throw new IllegalArgumentException("Cannot url encode " + value, e);
            }
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            throw new UnsupportedOperationException("getInputStream() is not implemented in this " + CustomHttpServletRequest.class.getSimpleName() + " wrapper");
        }

    }

note : queryString() requires to process ALL the values for each KEY and don't forget to encodeUrl() when adding your own param values, if required

As a limitation, if you call request.getParameterMap() or any method that would call request.getReader() and begin reading, you will prevent any further calls to request.setCharacterEncoding(...)

Automatically create an Enum based on values in a database lookup table?

I always like to write my own "custom enum". Than I have one class that is a little bit more complex, but I can reuse it:

public abstract class CustomEnum
{
    private readonly string _name;
    private readonly object _id;

    protected CustomEnum( string name, object id )
    {
        _name = name;
        _id = id;
    }

    public string Name
    {
        get { return _name; }
    }

    public object Id
    {
        get { return _id; }
    }

    public override string ToString()
    {
        return _name;
    }
}

public abstract class CustomEnum<TEnumType, TIdType> : CustomEnum
    where TEnumType : CustomEnum<TEnumType, TIdType>
{
    protected CustomEnum( string name, TIdType id )
        : base( name, id )
    { }

    public new TIdType Id
    {
        get { return (TIdType)base.Id; }
    }

    public static TEnumType FromName( string name )
    {
        try
        {
            return FromDelegate( entry => entry.Name.Equals( name ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal name for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static TEnumType FromId( TIdType id )
    {
        try
        {
            return FromDelegate( entry => entry.Id.Equals( id ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal id for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static IEnumerable<TEnumType> GetAll()
    {
        var elements = new Collection<TEnumType>();
        var infoArray = typeof( TEnumType ).GetFields( BindingFlags.Public | BindingFlags.Static );

        foreach (var info in infoArray)
        {
            var type = info.GetValue( null ) as TEnumType;
            elements.Add( type );
        }

        return elements;
    }

    protected static TEnumType FromDelegate( Predicate<TEnumType> predicate )
    {
        if(predicate == null)
            throw new ArgumentNullException( "predicate" );

        foreach (var entry in GetAll())
        {
            if (predicate( entry ))
                return entry;
        }

        throw new ArgumentException( "Element not found while using predicate" );
    }
}

Now I just need to create my enum I want to use:

 public sealed class SampleEnum : CustomEnum<SampleEnum, int>
    {
        public static readonly SampleEnum Element1 = new SampleEnum( "Element1", 1, "foo" );
        public static readonly SampleEnum Element2 = new SampleEnum( "Element2", 2, "bar" );

        private SampleEnum( string name, int id, string additionalText )
            : base( name, id )
        {
            AdditionalText = additionalText;
        }

        public string AdditionalText { get; private set; }
    }

At last I can use it like I want:

 static void Main( string[] args )
        {
            foreach (var element in SampleEnum.GetAll())
            {
                Console.WriteLine( "{0}: {1}", element, element.AdditionalText );
                Console.WriteLine( "Is 'Element2': {0}", element == SampleEnum.Element2 );
                Console.WriteLine();
            }

            Console.ReadKey();
        }

And my output would be:

Element1: foo
Is 'Element2': False

Element2: bar
Is 'Element2': True    

Regex matching beginning AND end strings

Scanner scanner = new Scanner(System.in);
String part = scanner.nextLine();
String line = scanner.nextLine();

String temp = "\\b" + part +"|"+ part + "\\b";
Pattern pattern = Pattern.compile(temp.toLowerCase());
Matcher matcher = pattern.matcher(line.toLowerCase());

System.out.println(matcher.find() ? "YES":"NO");

If you need to determine if any of the words of this text start or end with the sequence. you can use this regex \bsubstring|substring\b anythingsubstring substringanything anythingsubstringanything

Add characters to a string in Javascript

Simple use text = text + string2

Format numbers in django templates

Well I couldn't find a Django way, but I did find a python way from inside my model:

def format_price(self):
    import locale
    locale.setlocale(locale.LC_ALL, '')
    return locale.format('%d', self.price, True)

The import javax.persistence cannot be resolved

If anyone is using Maven, you'll need to add the dependency in the POM.XML file. The latest version as of this post is below:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

Serialize form data to JSON

The below code should help you out. :)

 //The function is based on http://css-tricks.com/snippets/jquery/serialize-form-to-json/
 <script src="//code.jquery.com/jquery-2.1.0.min.js"></script>

<script>
    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    $(function() {
        $('form.login').on('submit', function(e) {
          e.preventDefault();

          var formData = $(this).serializeObject();
          console.log(formData);
          $('.datahere').html(formData);
        });
    });
</script>

Getting value of selected item in list box as string

To retreive the value of all selected item in à listbox you can cast selected item in DataRowView and then select column where your data is:

foreach(object element in listbox.SelectedItems) {
    DataRowView row = (DataRowView)element;
    MessageBox.Show(row[0]);
}

Persist javascript variables across pages?

Yes, using Cookies. But be careful, don't put too much in them (I think there is a limit at 4kb). But a few variables are ok.

If you need to store considerably more than that, check out @Annie's great tips in the other answer. For small time data storage, I would say Cookies are the easiest thing.

Note that cookies are stored client side.

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

mysql> use mysql;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'my-password-here';

Try it once, it worked for me.

Bootstrap 4 - Inline List?

Bootstrap4

Remove a list’s bullets and apply some light margin with a combination of two classes, .list-inline and .list-inline-item.

<ul class="list-inline">
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>

Strings as Primary Keys in SQL Database

Don't worry about performance until you have got a simple and sound design that agrees with the subject matter that the data describes and fits well with the intended use of the data. Then, if performance problems emerge, you can deal with them by tweaking the system.

In this case, it's almost always better to go with a string as a natural primary key, provide you can trust it. Don't worry if it's a string, as long as the string is reasonably short, say about 25 characters max. You won't pay a big price in terms of performance.

Do the data entry people or automatic data sources always provide a value for the supposed natural key, or is sometimes omitted? Is it occasionally wrong in the input data? If so, how are errors detected and corrected?

Are the programmers and interactive users who specify queries able to use the natural key to get what they want?

If you can't trust the natural key, invent a surrogate. If you invent a surrogate, you might as well invent an integer. Then you have to worry about whther to conceal the surrogate from the user community. Some developers who didn't conceal the surrogate key came to regret it.

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

Windows 10 x64 released August 2015 - same issue arising. MSVCR110.dll is also found in the sysWOW64 folder (which is where I found it, copying to system32 does not help). To resolve:

  1. uninstall the x86 versions of VC 11 vcredist_x64/86.exe for 2012 and 2013
  2. uninstall WAMP Server 2.5
  3. delete (maybe back up first) the WAMP folder
  4. restart windows
  5. reinstall WAMP 2.5

Hopefully like me you have a MySQL database backup handy!

Delete the 'first' record from a table in SQL Server, without a WHERE condition

No, AFAIK, it's not possible to do it portably.

There's no defined "first" record anyway - on different SQL engines it's perfectly possible that "SELECT * FROM table" might return the results in a different order each time.

Having trouble setting working directory

This may help... use the following code and browse the folder you want to set as the working folder

setwd(choose.dir())

When do I use super()?

You would use it as the first line of a subclass constructor to call the constructor of its parent class.

For example:

public class TheSuper{
    public TheSuper(){
        eatCake();
    }
}

public class TheSub extends TheSuper{
    public TheSub(){
        super();
        eatMoreCake();
    }
}

Constructing an instance of TheSub would call both eatCake() and eatMoreCake()

Converting a JS object to an array using jQuery

ES8 way made easy:

The official documentation

_x000D_
_x000D_
    const obj = { x: 'xxx', y: 1 };_x000D_
    let arr = Object.values(obj); // ['xxx', 1]_x000D_
    console.log(arr);
_x000D_
_x000D_
_x000D_

Open a file with Notepad in C#

You need System.Diagnostics.Process.Start().

The simplest example:

Process.Start("notepad.exe", fileName);

More Generic Approach:

Process.Start(fileName);

The second approach is probably a better practice as this will cause the windows Shell to open up your file with it's associated editor. Additionally, if the file specified does not have an association, it'll use the Open With... dialog from windows.

Note to those in the comments, thankyou for your input. My quick n' dirty answer was slightly off, i've updated the answer to reflect the correct way.

How to hide status bar in Android

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // If the Android version is lower than Jellybean, use this call to hide
    // the status bar.
    if (Build.VERSION.SDK_INT < 16) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    } else {
       View decorView = getWindow().getDecorView();
       // Hide the status bar.
       int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
       decorView.setSystemUiVisibility(uiOptions);
       // Remember that you should never show the action bar if the
       // status bar is hidden, so hide that too if necessary.
       ActionBar actionBar = getActionBar();
       actionBar.hide();
    }

    setContentView(R.layout.activity_main);

}
...
}

remove duplicates from sql union

Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):

select * 
    from calls c join users u
        on c.assigned_to = u.user_id 
        or c.requestor_id = u.user_id
    where u.dept = 4

Sum across multiple columns with dplyr

Using reduce() from purrr is slightly faster than rowSums and definately faster than apply, since you avoid iterating over all the rows and just take advantage of the vectorized operations:

library(purrr)
library(dplyr)
iris %>% mutate(Petal = reduce(select(., starts_with("Petal")), `+`))

See this for timings

How to clear input buffer in C?

I encounter a problem trying to implement the solution

while ((c = getchar()) != '\n' && c != EOF) { }

I post a little adjustment 'Code B' for anyone who maybe have the same problem.

The problem was that the program kept me catching the '\n' character, independently from the enter character, here is the code that gave me the problem.

Code A

int y;

printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
   continue;
}
printf("\n%c\n", toupper(y));

and the adjustment was to 'catch' the (n-1) character just before the conditional in the while loop be evaluated, here is the code:

Code B

int y, x;

printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
   x = y;
}
printf("\n%c\n", toupper(x));

The possible explanation is that for the while loop to break, it has to assign the value '\n' to the variable y, so it will be the last assigned value.

If I missed something with the explanation, code A or code B please tell me, I’m barely new in c.

hope it helps someone

Can I redirect the stdout in python into some sort of string buffer?

Just to add to Ned's answer above: you can use this to redirect output to any object that implements a write(str) method.

This can be used to good effect to "catch" stdout output in a GUI application.

Here's a silly example in PyQt:

import sys
from PyQt4 import QtGui

class OutputWindow(QtGui.QPlainTextEdit):
    def write(self, txt):
        self.appendPlainText(str(txt))

app = QtGui.QApplication(sys.argv)
out = OutputWindow()
sys.stdout=out
out.show()
print "hello world !"

Set an empty DateTime variable

Option 1: Use a nullable DateTime?

Option 2: Use DateTime.MinValue

Personally, I'd prefer option 1.

Oracle: not a valid month

You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;

05/12/2015

Fastest way to count exact number of rows in a very large table?

You can try this sp_spaceused (Transact-SQL)

Displays the number of rows, disk space reserved, and disk space used by a table, indexed view, or Service Broker queue in the current database, or displays the disk space reserved and used by the whole database.

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

Define a behavior in your .config file:

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="debug">
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    ...
  </system.serviceModel>
</configuration>

Then apply the behavior to your service along these lines:

<configuration>
  <system.serviceModel>
    ...
    <services>
      <service name="MyServiceName" behaviorConfiguration="debug" />
    </services>
  </system.serviceModel>
</configuration>

You can also set it programmatically. See this question.

macro - open all files in a folder

You have to add this line just before loop

    MyFile = Dir
Loop

Drop multiple columns in pandas

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

Export multiple classes in ES6 modules

For exporting the instances of the classes you can use this syntax:

// export index.js
const Foo = require('./my/module/foo');
const Bar = require('./my/module/bar');

module.exports = {
    Foo : new Foo(),
    Bar : new Bar()
};

// import and run method
const {Foo,Bar} = require('module_name');
Foo.test();

How to upgrade Git to latest version on macOS?

I prefer not to alter the path hierarchy, but instead deal with git specifically...knowing that I'm never going to use old git to do what new git will now manage. This is a brute force solution.

NOTE: I installed XCode on Yosemite (10.10.2) clean first.

I then installed from the binary available on git-scm.com.

$ which git
/usr/bin/git
$ cd /usr/bin
$ sudo ln -sf /usr/local/git/bin/git
$ sudo ln -sf /usr/local/git/bin/git-credential-osxkeychain
$ sudo ln -sf /usr/local/git/bin/git-cvsserver
$ sudo ln -sf /usr/local/git/bin/git-receive-pack
$ sudo ln -sf /usr/local/git/bin/git-shell
$ sudo ln -sf /usr/local/git/bin/git-upload-archive
$ sudo ln -sf /usr/local/git/bin/git-upload-pack
$ ls -la
(you should see your new symlinks)

Which one is the best PDF-API for PHP?

personally i'd rather go with tcpdf which is an ehnanced and mantained version of fpdf.

How to prevent rm from reporting that a file was not found?

\rm -f file will never report not found.

isolating a sub-string in a string before a symbol in SQL Server 2008

DECLARE @test nvarchar(100)

SET @test = 'Foreign Tax Credit - 1997'

SELECT @test, left(@test, charindex('-', @test) - 2) AS LeftString,
    right(@test, len(@test) - charindex('-', @test) - 1)  AS RightString

How long to brute force a salted SHA-512 hash? (salt provided)

There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.

The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.

To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.

As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.

One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.

mysqldump exports only one table

Quoting this link: http://steveswanson.wordpress.com/2009/04/21/exporting-and-importing-an-individual-mysql-table/

  • Exporting the Table

To export the table run the following command from the command line:

mysqldump -p --user=username dbname tableName > tableName.sql

This will export the tableName to the file tableName.sql.

  • Importing the Table

To import the table run the following command from the command line:

mysql -u username -p -D dbname < tableName.sql

The path to the tableName.sql needs to be prepended with the absolute path to that file. At this point the table will be imported into the DB.

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

You can use the following code to get the current system date and time in C++ :

    #include <iostream>
    #include <time.h> //It may be #include <ctime> or any other header file depending upon
                     // compiler or IDE you're using 
    using namespace std;

    int main() {
       // current date/time based on current system
       time_t now = time(0);

       // convert now to string form
       string dt = ctime(&now);

       cout << "The local date and time is: " << dt << endl;
    return 0;
    }

PS: Visit this site for more information.

Total size of the contents of all the files in a directory

There are at least three ways to get the "sum total of all the data in files and subdirectories" in bytes that work in both Linux/Unix and Git Bash for Windows, listed below in order from fastest to slowest on average. For your reference, they were executed at the root of a fairly deep file system (docroot in a Magento 2 Enterprise installation comprising 71,158 files in 30,027 directories).

1.

$ time find -type f -printf '%s\n' | awk '{ total += $1 }; END { print total" bytes" }'
748660546 bytes

real    0m0.221s
user    0m0.068s
sys     0m0.160s

2.

$ time echo `find -type f -print0 | xargs -0 stat --format=%s | awk '{total+=$1} END {print total}'` bytes
748660546 bytes

real    0m0.256s
user    0m0.164s
sys     0m0.196s

3.

$ time echo `find -type f -exec du -bc {} + | grep -P "\ttotal$" | cut -f1 | awk '{ total += $1 }; END { print total }'` bytes
748660546 bytes

real    0m0.553s
user    0m0.308s
sys     0m0.416s


These two also work, but they rely on commands that don't exist on Git Bash for Windows:

1.

$ time echo `find -type f -printf "%s + " | dc -e0 -f- -ep` bytes
748660546 bytes

real    0m0.233s
user    0m0.116s
sys     0m0.176s

2.

$ time echo `find -type f -printf '%s\n' | paste -sd+ | bc` bytes
748660546 bytes

real    0m0.242s
user    0m0.104s
sys     0m0.152s


If you only want the total for the current directory, then add -maxdepth 1 to find.


Note that some of the suggested solutions don't return accurate results, so I would stick with the solutions above instead.

$ du -sbh
832M    .

$ ls -lR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'
Total: 583772525

$ find . -type f | xargs stat --format=%s | awk '{s+=$1} END {print s}'
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
4390471

$ ls -l| grep -v '^d'| awk '{total = total + $5} END {print "Total" , total}'
Total 968133

Is it possible to find out the users who have checked out my project on GitHub?

Go to the traffic section inside graphs. Here you can find how many unique visitors you have. Other than this there is no other way to know who exactly viewed your account.

database attached is read only

If you have tried all of this and still no luck, try the detach/attach again.

Redirecting to a certain route based on condition

I'm doing it using interceptors. I have created a library file which can be added to the index.html file. This way you'll have global error handling for your rest service calls and don't have to care about all errors individually. Further down I also pasted my basic-auth login library. There you can see that I also check for the 401 error and redirect to a different location. See lib/ea-basic-auth-login.js

lib/http-error-handling.js

/**
* @ngdoc overview
* @name http-error-handling
* @description
*
* Module that provides http error handling for apps.
*
* Usage:
* Hook the file in to your index.html: <script src="lib/http-error-handling.js"></script>
* Add <div class="messagesList" app-messages></div> to the index.html at the position you want to
* display the error messages.
*/
(function() {
'use strict';
angular.module('http-error-handling', [])
    .config(function($provide, $httpProvider, $compileProvider) {
        var elementsList = $();

        var showMessage = function(content, cl, time) {
            $('<div/>')
                .addClass(cl)
                .hide()
                .fadeIn('fast')
                .delay(time)
                .fadeOut('fast', function() { $(this).remove(); })
                .appendTo(elementsList)
                .text(content);
        };

        $httpProvider.responseInterceptors.push(function($timeout, $q) {
            return function(promise) {
                return promise.then(function(successResponse) {
                    if (successResponse.config.method.toUpperCase() != 'GET')
                        showMessage('Success', 'http-success-message', 5000);
                    return successResponse;

                }, function(errorResponse) {
                    switch (errorResponse.status) {
                        case 400:
                            showMessage(errorResponse.data.message, 'http-error-message', 6000);
                                }
                            }
                            break;
                        case 401:
                            showMessage('Wrong email or password', 'http-error-message', 6000);
                            break;
                        case 403:
                            showMessage('You don\'t have the right to do this', 'http-error-message', 6000);
                            break;
                        case 500:
                            showMessage('Server internal error: ' + errorResponse.data.message, 'http-error-message', 6000);
                            break;
                        default:
                            showMessage('Error ' + errorResponse.status + ': ' + errorResponse.data.message, 'http-error-message', 6000);
                    }
                    return $q.reject(errorResponse);
                });
            };
        });

        $compileProvider.directive('httpErrorMessages', function() {
            return {
                link: function(scope, element, attrs) {
                    elementsList.push($(element));
                }
            };
        });
    });
})();

css/http-error-handling.css

.http-error-message {
    background-color: #fbbcb1;
    border: 1px #e92d0c solid;
    font-size: 12px;
    font-family: arial;
    padding: 10px;
    width: 702px;
    margin-bottom: 1px;
}

.http-error-validation-message {
    background-color: #fbbcb1;
    border: 1px #e92d0c solid;
    font-size: 12px;
    font-family: arial;
    padding: 10px;
    width: 702px;
    margin-bottom: 1px;
}

http-success-message {
    background-color: #adfa9e;
    border: 1px #25ae09 solid;
    font-size: 12px;
    font-family: arial;
    padding: 10px;
    width: 702px;
    margin-bottom: 1px;
}

index.html

<!doctype html>
<html lang="en" ng-app="cc">
    <head>
        <meta charset="utf-8">
        <title>yourapp</title>
        <link rel="stylesheet" href="css/http-error-handling.css"/>
    </head>
    <body>

<!-- Display top tab menu -->
<ul class="menu">
  <li><a href="#/user">Users</a></li>
  <li><a href="#/vendor">Vendors</a></li>
  <li><logout-link/></li>
</ul>

<!-- Display errors -->
<div class="http-error-messages" http-error-messages></div>

<!-- Display partial pages -->
<div ng-view></div>

<!-- Include all the js files. In production use min.js should be used -->
<script src="lib/angular114/angular.js"></script>
<script src="lib/angular114/angular-resource.js"></script>
<script src="lib/http-error-handling.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>

lib/ea-basic-auth-login.js

Nearly same can be done for the login. Here you have the answer to the redirect ($location.path("/login")).

/**
* @ngdoc overview
* @name ea-basic-auth-login
* @description
*
* Module that provides http basic authentication for apps.
*
* Usage:
* Hook the file in to your index.html: <script src="lib/ea-basic-auth-login.js">  </script>
* Place <ea-login-form/> tag in to your html login page
* Place <ea-logout-link/> tag in to your html page where the user has to click to logout
*/
(function() {
'use strict';
angular.module('ea-basic-auth-login', ['ea-base64-login'])
    .config(['$httpProvider', function ($httpProvider) {
        var ea_basic_auth_login_interceptor = ['$location', '$q', function($location, $q) {
            function success(response) {
                return response;
            }

            function error(response) {
                if(response.status === 401) {
                    $location.path('/login');
                    return $q.reject(response);
                }
                else {
                    return $q.reject(response);
                }
            }

            return function(promise) {
                return promise.then(success, error);
            }
        }];
        $httpProvider.responseInterceptors.push(ea_basic_auth_login_interceptor);
    }])
    .controller('EALoginCtrl', ['$scope','$http','$location','EABase64Login', function($scope, $http, $location, EABase64Login) {
        $scope.login = function() {
            $http.defaults.headers.common['Authorization'] = 'Basic ' + EABase64Login.encode($scope.email + ':' + $scope.password);
            $location.path("/user");
        };

        $scope.logout = function() {
            $http.defaults.headers.common['Authorization'] = undefined;
            $location.path("/login");
        };
    }])
    .directive('eaLoginForm', [function() {
        return {
            restrict:   'E',
            template:   '<div id="ea_login_container" ng-controller="EALoginCtrl">' +
                        '<form id="ea_login_form" name="ea_login_form" novalidate>' +
                        '<input id="ea_login_email_field" class="ea_login_field" type="text" name="email" ng-model="email" placeholder="E-Mail"/>' +
                        '<br/>' +
                        '<input id="ea_login_password_field" class="ea_login_field" type="password" name="password" ng-model="password" placeholder="Password"/>' +
                        '<br/>' +
                        '<button class="ea_login_button" ng-click="login()">Login</button>' +
                        '</form>' +
                        '</div>',
            replace: true
        };
    }])
    .directive('eaLogoutLink', [function() {
        return {
            restrict: 'E',
            template: '<a id="ea-logout-link" ng-controller="EALoginCtrl" ng-click="logout()">Logout</a>',
            replace: true
        }
    }]);

angular.module('ea-base64-login', []).
    factory('EABase64Login', function() {
        var keyStr = 'ABCDEFGHIJKLMNOP' +
            'QRSTUVWXYZabcdef' +
            'ghijklmnopqrstuv' +
            'wxyz0123456789+/' +
            '=';

        return {
            encode: function (input) {
                var output = "";
                var chr1, chr2, chr3 = "";
                var enc1, enc2, enc3, enc4 = "";
                var i = 0;

                do {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);

                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;

                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }

                    output = output +
                        keyStr.charAt(enc1) +
                        keyStr.charAt(enc2) +
                        keyStr.charAt(enc3) +
                        keyStr.charAt(enc4);
                    chr1 = chr2 = chr3 = "";
                    enc1 = enc2 = enc3 = enc4 = "";
                } while (i < input.length);

                return output;
            },

            decode: function (input) {
                var output = "";
                var chr1, chr2, chr3 = "";
                var enc1, enc2, enc3, enc4 = "";
                var i = 0;

                // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
                var base64test = /[^A-Za-z0-9\+\/\=]/g;
                if (base64test.exec(input)) {
                    alert("There were invalid base64 characters in the input text.\n" +
                        "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
                        "Expect errors in decoding.");
                }
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

                do {
                    enc1 = keyStr.indexOf(input.charAt(i++));
                    enc2 = keyStr.indexOf(input.charAt(i++));
                    enc3 = keyStr.indexOf(input.charAt(i++));
                    enc4 = keyStr.indexOf(input.charAt(i++));

                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;

                    output = output + String.fromCharCode(chr1);

                    if (enc3 != 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 != 64) {
                        output = output + String.fromCharCode(chr3);
                    }

                    chr1 = chr2 = chr3 = "";
                    enc1 = enc2 = enc3 = enc4 = "";

                } while (i < input.length);

                return output;
            }
        };
    });
})();

How to make Excel VBA variables available to multiple macros?

You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules

For details on Scope of variables refer this link

Please copy the below code into any module, save the workbook and then run the code.

Here is what code does

  • The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.

  • I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.

Dim wbA As Workbook
Dim wbB As Workbook

Sub MySubRoutine()
    Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String

    folderPath = ThisWorkbook.Path & "\"
    fileNm1 = "file1.xlsx"
    fileNm2 = "file2.xlsx"

    filePath1 = folderPath & fileNm1
    filePath2 = folderPath & fileNm2

    If IsWorkBookOpen(filePath1) Then
        Set wbA = Workbooks(fileNm1)
    Else
        Set wbA = Workbooks.Open(filePath1)
    End If


    If IsWorkBookOpen(filePath2) Then
        Set wbB = Workbooks.Open(fileNm2)
    Else
        Set wbB = Workbooks.Open(filePath2)
    End If


    ' your code here
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0: IsWorkBookOpen = False
    Case 70: IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Using Prompt to select the file use below code.

Dim wbA As Workbook
Dim wbB As Workbook

Sub MySubRoutine()
    Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String

    Dim filePath As String
    cmdBrowse_Click filePath, 1

    filePath1 = filePath

    'reset the variable
    filePath = vbNullString

    cmdBrowse_Click filePath, 2
    filePath2 = filePath

   fileNm1 = GetFileName(filePath1, "\")
   fileNm2 = GetFileName(filePath2, "\")

    If IsWorkBookOpen(filePath1) Then
        Set wbA = Workbooks(fileNm1)
    Else
        Set wbA = Workbooks.Open(filePath1)
    End If


    If IsWorkBookOpen(filePath2) Then
        Set wbB = Workbooks.Open(fileNm2)
    Else
        Set wbB = Workbooks.Open(filePath2)
    End If


    ' your code here
End Sub

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0: IsWorkBookOpen = False
    Case 70: IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)

    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Select workbook " & num
    fd.InitialView = msoFileDialogViewSmallIcons

    Dim FileChosen As Integer

    FileChosen = fd.Show

    fd.Filters.Clear
    fd.Filters.Add "Excel macros", "*.xlsx"


    fd.FilterIndex = 1



    If FileChosen <> -1 Then
        MsgBox "You chose cancel"
        filePath = ""
    Else
        filePath = fd.SelectedItems(1)
    End If

End Sub

Function GetFileName(fullName As String, pathSeparator As String) As String

    Dim i As Integer
    Dim iFNLenght As Integer
    iFNLenght = Len(fullName)

    For i = iFNLenght To 1 Step -1
        If Mid(fullName, i, 1) = pathSeparator Then Exit For
    Next

    GetFileName = Right(fullName, iFNLenght - i)

End Function

Git - how delete file from remote repository

  1. If you want to push a deleted file to remote

git add 'deleted file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote and locally

git rm 'file name'

git commit -m'message'

git push -u origin branch

  1. If you want to delete a file from remote only

git rm --cached 'file name'

git commit -m'message'

git push -u origin branch

ASP.NET Core 1.0 on IIS error 502.5

I got this working with a hard reset of IIS (I had only just installed the hosting package).

Turns out that just pressing 'Restart' in IIS Manager isn't enough. I just had to open a command prompt and type 'iisreset'

Why does the 'int' object is not callable error occur when using the sum() function?

This means that somewhere else in your code, you have something like:

sum = 0

Which shadows the builtin sum (which is callable) with an int (which isn't).

Android: Changing Background-Color of the Activity (Main View)

if you put your full code here so i can help you. if your setting the listener in XML and calling the set background color on View so it will change the background color of the view means it ur Botton so put ur listener in ur activity and then change the color of your view

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

Command find_package has two modes: Module mode and Config mode. You are trying to use Module mode when you actually need Config mode.

Module mode

Find<package>.cmake file located within your project. Something like this:

CMakeLists.txt
cmake/FindFoo.cmake
cmake/FindBoo.cmake

CMakeLists.txt content:

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
find_package(Foo REQUIRED) # FOO_INCLUDE_DIR, FOO_LIBRARIES
find_package(Boo REQUIRED) # BOO_INCLUDE_DIR, BOO_LIBRARIES

include_directories("${FOO_INCLUDE_DIR}")
include_directories("${BOO_INCLUDE_DIR}")
add_executable(Bar Bar.hpp Bar.cpp)
target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES})

Note that CMAKE_MODULE_PATH has high priority and may be usefull when you need to rewrite standard Find<package>.cmake file.

Config mode (install)

<package>Config.cmake file located outside and produced by install command of other project (Foo for example).

foo library:

> cat CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)
project(Foo)

add_library(foo Foo.hpp Foo.cpp)
install(FILES Foo.hpp DESTINATION include)
install(TARGETS foo DESTINATION lib)
install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo)

Simplified version of config file:

> cat FooConfig.cmake 
add_library(foo STATIC IMPORTED)
find_library(FOO_LIBRARY_PATH foo HINTS "${CMAKE_CURRENT_LIST_DIR}/../../")
set_target_properties(foo PROPERTIES IMPORTED_LOCATION "${FOO_LIBRARY_PATH}")

By default project installed in CMAKE_INSTALL_PREFIX directory:

> cmake -H. -B_builds
> cmake --build _builds --target install
-- Install configuration: ""
-- Installing: /usr/local/include/Foo.hpp
-- Installing: /usr/local/lib/libfoo.a
-- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake

Config mode (use)

Use find_package(... CONFIG) to include FooConfig.cmake with imported target foo:

> cat CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)
project(Boo)

# import library target `foo`
find_package(Foo CONFIG REQUIRED)

add_executable(boo Boo.cpp Boo.hpp)
target_link_libraries(boo foo)
> cmake -H. -B_builds -DCMAKE_VERBOSE_MAKEFILE=ON
> cmake --build _builds
Linking CXX executable Boo
/usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a

Note that imported target is highly configurable. See my answer.

Update

Make REST API call in Swift

let headers = [
                "cache-control": "no-cache",
                "postman-token": "6f8a-12c6-87a1-ac0f25d6385a"
            ]

            let request = NSMutableURLRequest(url: NSURL(string: "Your url string")! as URL,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            request.httpMethod = "GET"
            request.allHTTPHeaderFields = headers

            let session = URLSession.shared
            let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
                if error == nil && data != nil {
                    do {
                        // Convert NSData to Dictionary where keys are of type String, and values are of any type
                        let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
                        print(json)

                        //do your stuff

                      //  completionHandler(true)

                    } catch {
                       // completionHandler(false)
                    }
                }
                else if error != nil
                {
                    //completionHandler(false)
                }
            }).resume()
            }

How do I convert a float to an int in Objective C?

Here's a more terse approach that was introduced in 2012:

myInt = @(myFloat).intValue;

JS: Uncaught TypeError: object is not a function (onclick)

Since the behavior is kind of strange, I have done some testing on the behavior, and here's my result:

TL;DR

If you are:

  • In a form, and
  • uses onclick="xxx()" on an element
  • don't add id="xxx" or name="xxx" to that element
    • (e.g. <form><button id="totalbandwidth" onclick="totalbandwidth()">BAD</button></form> )

Here's are some test and their result:

Control sample (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

Add id to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button id="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add name to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button name="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add value to button (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <input type="button" value="totalbandwidth" onclick="totalbandwidth()" />SUCCESS
</form>
_x000D_
_x000D_
_x000D_

Add id to button, but not in a form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<button id="totalbandwidth" onclick="totalbandwidth()">SUCCESS</button>
_x000D_
_x000D_
_x000D_

Add id to another element inside the form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("The answer is no, the span will not affect button"); }
_x000D_
<form onsubmit="return false;">
<span name="totalbandwidth" >Will this span affect button? </span>
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

What does the PHP error message "Notice: Use of undefined constant" mean?

You missed putting single quotes around your array keys:

$_POST[email]

should be:

$_POST['email']

C compile error: "Variable-sized object may not be initialized"

After declaring the array

int boardAux[length][length];

the simplest way to assign the initial values as zero is using for loop, even if it may be a bit lengthy

int i, j;
for (i = 0; i<length; i++)
{
    for (j = 0; j<length; j++)
        boardAux[i][j] = 0;
}

Is it possible to display my iPhone on my computer monitor?

Do not we have an app which can stream the digital movie from iOS devices like iPhone or iPad to be played on a high definition LED or Plasma TV?

I know of an app air video server which can be used to display content played on computer or laptop on iOS device. But is there any app that can do the reverse & play the digital content from iphone to LED tv .

How to use mongoimport to import csv

C:\wamp\mongodb\bin>mongoexport --db proj_mmm --collection offerings --csv --fieldFile offerings_fields.txt --out offerings.csv

Codeigniter displays a blank page instead of error messages

Make sure you don't have a blank index.html file in your root folder. It happens :)

Making Python loggers output all messages to stdout in addition to log file

I simplified my source code (whose original version is OOP and uses a configuration file), to give you an alternative solution to @EliasStrehle's one, without using the dictConfig (thus easiest to integrate with existing source code):

import logging
import sys


def create_stream_handler(stream, formatter, level, message_filter=None):
    handler = logging.StreamHandler(stream=stream)
    handler.setLevel(level)
    handler.setFormatter(formatter)
    if message_filter:
        handler.addFilter(message_filter)
    return handler


def configure_logger(logger: logging.Logger, enable_console: bool = True, enable_file: bool = True):
    if not logger.handlers:
        if enable_console:
            message_format: str = '{asctime:20} {name:16} {levelname:8} {message}'
            date_format: str = '%Y/%m/%d %H:%M:%S'
            level: int = logging.DEBUG
            formatter = logging.Formatter(message_format, date_format, '{')

            # Configures error output (from Warning levels).
            error_output_handler = create_stream_handler(sys.stderr, formatter,
                                                         max(level, logging.WARNING))
            logger.addHandler(error_output_handler)

            # Configures standard output (from configured Level, if lower than Warning,
            #  and excluding everything from Warning and higher).
            if level < logging.WARNING:
                standard_output_filter = lambda record: record.levelno < logging.WARNING
                standard_output_handler = create_stream_handler(sys.stdout, formatter, level,
                                                                standard_output_filter)
                logger.addHandler(standard_output_handler)

        if enable_file:
            message_format: str = '{asctime:20} {name:16} {levelname:8} {message}'
            date_format: str = '%Y/%m/%d %H:%M:%S'
            level: int = logging.DEBUG
            output_file: str = '/tmp/so_test.log'

            handler = logging.FileHandler(output_file)
            formatter = logging.Formatter(message_format, date_format, '{')
            handler.setLevel(level)
            handler.setFormatter(formatter)
            logger.addHandler(handler)

This is a very simple way to test it:

logger: logging.Logger = logging.getLogger('MyLogger')
logger.setLevel(logging.DEBUG)
configure_logger(logger, True, True)
logger.debug('Debug message ...')
logger.info('Info message ...')
logger.warning('Warning ...')
logger.error('Error ...')
logger.fatal('Fatal message ...')

C# - insert values from file into two arrays

string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Try this:

$('select[name="' + name + '"] option:selected').val();

This will get the selected value of your menu.

Using git commit -a with vim

Instead of trying to learn vim, use a different easier editor (like nano, for example). As much as I like vim, I do not think using it in this case is the solution. It takes dedication and time to master it.

git config core.editor "nano"

Entity Framework The underlying provider failed on Open

I saw this error when a colleague was trying to connect to a database that was protected behind a VPN. The user had unknownling switched to a wireless network that did not have VPN access. One way to test this scenario is to see if you can establish a connection in another means, such as SSMS, and see if that fails as well.

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

Is this what you're looking for?

#include <chrono>
#include <iostream>

int main()
{
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto t0 = Time::now();
    auto t1 = Time::now();
    fsec fs = t1 - t0;
    ms d = std::chrono::duration_cast<ms>(fs);
    std::cout << fs.count() << "s\n";
    std::cout << d.count() << "ms\n";
}

which for me prints out:

6.5e-08s
0ms

SQL Stored Procedure set variables using SELECT

One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.

SELECT @currentTerm = currentterm,
       @termID = termid,
       @endDate = enddate
FROM   table1
WHERE  iscurrent = 1

IF( @@ROWCOUNT <> 1 )
  BEGIN
      RAISERROR ('Unexpected number of matching rows',
                 16,
                 1)

      RETURN
  END  

How to display pandas DataFrame of floats using a format string for columns?

summary:


    df = pd.DataFrame({'money': [100.456, 200.789], 'share': ['100,000', '200,000']})
    print(df)
    print(df.to_string(formatters={'money': '${:,.2f}'.format}))
    for col_name in ('share',):
        df[col_name] = df[col_name].map(lambda p: int(p.replace(',', '')))
    print(df)
    """
        money    share
    0  100.456  100,000
    1  200.789  200,000

        money    share
    0 $100.46  100,000
    1 $200.79  200,000

         money   share
    0  100.456  100000
    1  200.789  200000
    """

Scala Doubles, and Precision

How about :

 val value = 1.4142135623730951

//3 decimal places
println((value * 1000).round / 1000.toDouble)

//4 decimal places
println((value * 10000).round / 10000.toDouble)

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

jQuery set radio button

You can try the following code:

$("input[name=cols][value=" + value + "]").attr('checked', 'checked');

This will set the attribute checked for the radio columns and value as specified.

Unable to connect to SQL Server instance remotely

  • To enable mixed authentication you can change the following registry key:

    HKLM\Software\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer\LoginMode
    

    Update the value to 2 and restart the Sql Server service to allow mixed authentication. Note that MSSQL.1 might need to be updated to reflect the number of the SQL Server Instance you are attempting to change.

  • A reason for connection errors can be a virus scanner installed on the server which blocks sqlserver.exe.

  • Another reason can be that the SQL Server Browser service is not running. When this service is not running you cannot connect on named instances (when they are using dynamic ports).

  • It is also possible that Sql Server is not setup to listen to TCP connections and only allows named pipes.

    1. In the Start Menu, open Programs > Microsoft SQL Server 2008 > Configuration Tools > SQL Server Surface Area Configuration
    2. In the Surface Area Configuration utility, click the link "SQL Server Configuration Manager"
    3. Expand "SQL Server Network Configuration" and select Protocols.
    4. Enable TCP/IP. If you need Named Pipes, then you can enable them here as well.
  • Last but not least, the Windows firewall needs to allow connections to SQL Server

    1. Add an exception for sqlserver.exe when you use the "Dynamic Port" system.
    2. Otherwise you can put exceptions for the SQL Server ports (default port 1433)
    3. Also add an exception for the SQL Server Browser. (udp port 1434)

More information:

As a last note, SqlLocalDB only supports named pipes, so you can not connect to it over the network.

IOException: Too many open files

Aside from looking into root cause issues like file leaks, etc. in order to do a legitimate increase the "open files" limit and have that persist across reboots, consider editing

/etc/security/limits.conf

by adding something like this

jetty soft nofile 2048
jetty hard nofile 4096

where "jetty" is the username in this case. For more details on limits.conf, see http://linux.die.net/man/5/limits.conf

log off and then log in again and run

ulimit -n

to verify that the change has taken place. New processes by this user should now comply with this change. This link seems to describe how to apply the limit on already running processes but I have not tried it.

The default limit 1024 can be too low for large Java applications.

JPA Native Query select and cast object

First of all create a model POJO

import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "class_id")
    public int classId;
    @Column(name = "user_name")
    public String userName;
    //getter,setter
}

Controller

import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;

@RestController
public class HomeController {
    @PersistenceUnit
    private EntityManagerFactory emf;

    @GetMapping("/")
    public List<StdUser> actionIndex() {
        EntityManager em = emf.createEntityManager(); // Without parameter
        List<StdUser> arr_cust = (List<StdUser>)em
                .createQuery("SELECT c FROM StdUser c")
                .getResultList();
        return arr_cust;
    }

    @GetMapping("/paramter")
    public List actionJoin() {
        int id = 3;
        String userName = "Suresh Shrestha";
        EntityManager em = emf.createEntityManager(); // With parameter
        List arr_cust = em
                .createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
                .setParameter("Id",id)
                .setParameter("UserName",userName)
                .getResultList();
        return arr_cust;
    }
}

npm install from Git in a specific version

If you're doing this with more than one module and want to have more control over versions, you should look into having your own private npm registry.

This way you can npm publish your modules to your private npm registry and use package.json entries the same way you would for public modules.

https://docs.npmjs.com/files/package.json#dependencies

What is parsing in terms that a new programmer would understand?

What is parsing?

In computer science, parsing is the process of analysing text to determine if it belongs to a specific language or not (i.e. is syntactically valid for that language's grammar). It is an informal name for the syntactic analysis process.

For example, suppose the language a^n b^n (which means same number of characters A followed by the same number of characters B). A parser for that language would accept AABB input and reject the AAAB input. That is what a parser does.

In addition, during this process a data structure could be created for further processing. In my previous example, it could, for instance, to store the AA and BB in two separate stacks.

Anything that happens after it, like giving meaning to AA or BB, or transform it in something else, is not parsing. Giving meaning to parts of an input sequence of tokens is called semantic analysis.

What isn't parsing?

  • Parsing is not transform one thing into another. Transforming A into B, is, in essence, what a compiler does. Compiling takes several steps, parsing is only one of them.
  • Parsing is not extracting meaning from a text. That is semantic analysis, a step of the compiling process.

What is the simplest way to understand it?

I think the best way for understanding the parsing concept is to begin with the simpler concepts. The simplest one in language processing subject is the finite automaton. It is a formalism to parsing regular languages, such as regular expressions.

It is very simple, you have an input, a set of states and a set of transitions. Consider the following language built over the alphabet { A, B }, L = { w | w starts with 'AA' or 'BB' as substring }. The automaton below represents a possible parser for that language whose all valid words starts with 'AA' or 'BB'.

    A-->(q1)--A-->(qf)
   /  
 (q0)    
   \          
    B-->(q2)--B-->(qf)

It is a very simple parser for that language. You start at (q0), the initial state, then you read a symbol from the input, if it is A then you move to (q1) state, otherwise (it is a B, remember the remember the alphabet is only A and B) you move to (q2) state and so on. If you reach (qf) state, then the input was accepted.

As it is visual, you only need a pencil and a piece of paper to explain what a parser is to anyone, including a child. I think the simplicity is what makes the automata the most suitable way to teaching language processing concepts, such as parsing.

Finally, being a Computer Science student, you will study such concepts in-deep at theoretical computer science classes such as Formal Languages and Theory of Computation.

How do I get the name of the rows from the index of a data frame?

If you want to pull out only the index values for certain integer-based row-indices, you can do something like the following using the iloc method:

In [28]: temp
Out[28]:
       index                 time  complete
row_0      2  2014-10-22 01:00:00         0
row_1      3  2014-10-23 14:00:00         0
row_2      4  2014-10-26 08:00:00         0
row_3      5  2014-10-26 10:00:00         0
row_4      6  2014-10-26 11:00:00         0

In [29]: temp.iloc[[0,1,4]].index
Out[29]: Index([u'row_0', u'row_1', u'row_4'], dtype='object')

In [30]: temp.iloc[[0,1,4]].index.tolist()
Out[30]: ['row_0', 'row_1', 'row_4']

Wait one second in running program

The Best way to wait without freezing your main thread is using the Task.Delay function.

So your code will look like this

var t = Task.Run(async delegate
{              
    dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
    dataGridView1.Refresh();
    await Task.Delay(1000);             
});

AddTransient, AddScoped and AddSingleton Services Differences

After looking for an answer for this question I found a brilliant explanation with an example that I would like to share with you.

You can watch a video that demonstrate the differences HERE

In this example we have this given code:

public interface IEmployeeRepository
{
    IEnumerable<Employee> GetAllEmployees();
    Employee Add(Employee employee);
}

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class MockEmployeeRepository : IEmployeeRepository
{
    private List<Employee> _employeeList;

    public MockEmployeeRepository()
    {
        _employeeList = new List<Employee>()
    {
        new Employee() { Id = 1, Name = "Mary" },
        new Employee() { Id = 2, Name = "John" },
        new Employee() { Id = 3, Name = "Sam" },
    };
    }

    public Employee Add(Employee employee)
    {
        employee.Id = _employeeList.Max(e => e.Id) + 1;
        _employeeList.Add(employee);
        return employee;
    }

    public IEnumerable<Employee> GetAllEmployees()
    {
        return _employeeList;
    }
}

HomeController

public class HomeController : Controller
{
    private IEmployeeRepository _employeeRepository;

    public HomeController(IEmployeeRepository employeeRepository)
    {
        _employeeRepository = employeeRepository;
    }

    [HttpGet]
    public ViewResult Create()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Create(Employee employee)
    {
        if (ModelState.IsValid)
        {
            Employee newEmployee = _employeeRepository.Add(employee);
        }

        return View();
    }
}

Create View

@model Employee
@inject IEmployeeRepository empRepository

<form asp-controller="home" asp-action="create" method="post">
    <div>
        <label asp-for="Name"></label>
        <div>
            <input asp-for="Name">
        </div>
    </div>

    <div>
        <button type="submit">Create</button>
    </div>

    <div>
        Total Employees Count = @empRepository.GetAllEmployees().Count().ToString()
    </div>
</form>

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IEmployeeRepository, MockEmployeeRepository>();
}

Copy-paste this code and press on the create button in the view and switch between AddSingleton , AddScoped and AddTransient you will get each time a different result that will might help you understand this.

AddSingleton() - As the name implies, AddSingleton() method creates a Singleton service. A Singleton service is created when it is first requested. This same instance is then used by all the subsequent requests. So in general, a Singleton service is created only one time per application and that single instance is used throughout the application life time.

AddTransient() - This method creates a Transient service. A new instance of a Transient service is created each time it is requested.

AddScoped() - This method creates a Scoped service. A new instance of a Scoped service is created once per request within the scope. For example, in a web application it creates 1 instance per each http request but uses the same instance in the other calls within that same web request.

Docker container not starting (docker start)

What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

To do this after half day searching did it using:

docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb

This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

To login in mysql after that can use:

mysql -u root -proot -h 127.0.0.1 -P3301

Used sources are:

The answer of Iarks in this article /using -it -d was the key :) /

how-to-install-and-use-docker-on-ubuntu-16-04

installing-and-using-mariadb-via-docker

mariadb-and-docker-use-cases-part-1

Good luck all!

Emulate a 403 error page

Seen a lot of the answers, but the correct one is to provide the full options for the header function call as per the php manual

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

If you invoke with

header('HTTP/1.0 403 Forbidden', true, 403);

the normal behavior of HTTP 403 as configured with Apache or any other server would follow.

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

While I'm all for unblocking people's work issues, I don't think "push --force" or "--allow_unrelated_histories" should be taught to new users as general solutions because they can cause real havoc to a repository when one uses them without understand why things aren't working in the first place.

When you have a situation like this where you started with a local repository, and want to make a remote on GitHub to share your work with, there is something to watch out for.

When you create the new online repository, there's an option "Initialize this repository with a README". If you read the fine print, it says "Skip this step if you’re importing an existing repository."

You may have checked that box. Or similarly, you made an add/commit online before you attempted an initial push. What happens is you create a unique commit history in each place and they can't be reconciled without the special allowance mentioned in Nevermore's answer (because git doesn't want you to operate that way). You can follow some of the advice mentioned here, or more simply just don't check that option next time you want to link some local files to a brand new remote; keeping the remote clean for that initial push.

Reference: my first experience with git + hub was to run into this same problem and do a lot of learning to understand what had happened and why.

How do I log a Python error with debug information?

This answer builds up from the above excellent ones.

In most applications, you won't be calling logging.exception(e) directly. Most likely you have defined a custom logger specific for your application or module like this:

# Set the name of the app or module
my_logger = logging.getLogger('NEM Sequencer')
# Set the log level
my_logger.setLevel(logging.INFO)

# Let's say we want to be fancy and log to a graylog2 log server
graylog_handler = graypy.GELFHandler('some_server_ip', 12201)
graylog_handler.setLevel(logging.INFO)
my_logger.addHandler(graylog_handler)

In this case, just use the logger to call the exception(e) like this:

try:
    1/0
except ZeroDivisionError, e:
    my_logger.exception(e)

How to compare if two structs, slices or maps are equal?

If you're comparing them in unit test, a handy alternative is EqualValues function in testify.

Merge two Excel tables Based on matching data in Columns

Put the table in the second image on Sheet2, columns D to F.

In Sheet1, cell D2 use the formula

=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")

copy across and down.

Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

enter image description here

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

I just did:

public static bool Implements<I>(this Type source) where I : class
{
  return typeof(I).IsAssignableFrom(source);
}

I wish I could have said where I : interface, but interface is not a generic parameter constraint option. class is as close as it gets.

Usage:

if(MyType.Implements<IInitializable>())
  MyCollection.Initialize();

I just said Implements because that's more intuitive. I always get IsAssignableFrom flip-flopped.

Using GroupBy, Count and Sum in LINQ Lambda Expressions

    var ListByOwner = list.GroupBy(l => l.Owner)
                          .Select(lg => 
                                new { 
                                    Owner = lg.Key, 
                                    Boxes = lg.Count(),
                                    TotalWeight = lg.Sum(w => w.Weight), 
                                    TotalVolume = lg.Sum(w => w.Volume) 
                                });

Babel 6 regeneratorRuntime is not defined

For people looking to use the babel-polyfill version 7^ do this with webpack ver3^.

Npm install the module npm i -D @babel/polyfill

Then in your webpack file in your entry point do this

entry: ['@babel/polyfill', path.resolve(APP_DIR, 'App.js')],

Hashmap does not work with int, char

Generics only support object types, not primitives. Unlike C++ templates, generics don't involve code generatation and there is only one HashMap code regardless of the number of generic types of it you use.

Trove4J gets around this by pre-generating selected collections to use primitives and supports TCharIntHashMap which to can wrap to support the Map<Character, Integer> if you need to.

TCharIntHashMap: An open addressed Map implementation for char keys and int values.

How to select/get drop down option in Selenium 2

Try using:

selenium.select("id=items","label=engineering")

or

selenium.select("id=items","index=3")

How can I get the current user's username in Bash?

Two commands:

  1. id prints the user id along with the groups. Format: uid=usernumber(username) ...

  2. whoami gives the current user name

UIView touch event in controller

For swift 4

@IBOutlet weak var someView: UIView!  
let gesture = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
self.someView.addGestureRecognizer(gesture)

@objc func someAction(_ sender:UITapGestureRecognizer){
    print("view was clicked")
}

Declare an empty two-dimensional array in Javascript?

I know this is an old thread but I'd like to suggest using an array of objects rather than an array of arrays. I think it make the code simpler to understand and update.

_x000D_
_x000D_
// Use meaningful variable names like 'points', 
// anything better than a bad pirate joke, 'arr'!
var points = [];

// Create an object literal, then add it to the array
var point = {x: 0, y: 0};
points.push(point);

// Create and add the object to the array in 1 line
points.push({x:5, y:5});

// Create the object from local variables 
var x = 10;
var y = 8;
points.push({x, y});

// Ask the user for a point too
var response = prompt("Please enter a coordinate point. Example: 3,8");
var coords = response.split(",").map(Number);
points.push({x: coords[0], y: coords[1]});

// Show the results
var canvas = document.getElementById('graph');
var painter = canvas.getContext("2d");
var width = canvas.width, height = canvas.height;
var scale = 10, radius = 3.5, deg0 = 0, deg360 = 2 * Math.PI;

painter.beginPath();
for (var point of points) {
    var x = point.x * scale + scale;
    var y = height - point.y * scale - scale;
    painter.moveTo(x + radius, y);
    painter.arc(x, y, radius, deg0, deg360);
    painter.fillText(`${point.x}, ${point.y}`, x + radius + 1, y + radius + 1);
}
painter.stroke();
_x000D_
<canvas id="graph" width="150" height="150" style="border: 1px solid red;"></canvas>
_x000D_
_x000D_
_x000D_

Plot a legend outside of the plotting area in base graphics?

Try layout() which I have used for this in the past by simply creating an empty plot below, properly scaled at around 1/4 or so and placing the legend parts manually in it.

There are some older questions here about legend() which should get you started.

How to rsync only a specific list of files?

Edit: atp's answer below is better. Please use that one!

You might have an easier time, if you're looking for a specific list of files, putting them directly on the command line instead:

# rsync -avP -e ssh `cat deploy/rsync_include.txt` [email protected]:/var/www/

This is assuming, however, that your list isn't so long that the command line length will be a problem and that the rsync_include.txt file contains just real paths (i.e. no comments, and no regexps).

Redirect to external URL with return in laravel

You should be able to redirect to the url like this

return Redirect::to($url);

You can read about Redirects in the Laravel docs here.