Programs & Examples On #Line breaks

Whitespace that forces text layout to continue at the start of the next line.

How to break lines at a specific character in Notepad++?

Let's assume ], is the character where we wanted to break at

  1. Open notePad++
  2. Open Find window Ctrl+F
  3. Switch to Replace Tab
  4. Choose Search Mode to Extended
  5. Type ], in Find What field
  6. Type \nin Replace with field
  7. Hit Replace All
  8. Boom

How to remove line breaks (no characters!) from the string?

I use 3 lines to do this job, so consider $s as your "stuff"...

$s=str_replace(chr(10),'',$s);
$s=str_replace(chr(13),'',$s);
$s=str_replace("\r\n"),'',$s);

How to remove line breaks from a file in Java?

str = str.replaceAll("\\r\\n|\\r|\\n", " ");

Worked perfectly for me after searching a lot, having failed with every other line.

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

Here's a C# function that prepends a text line to an existing text blob, delimited by CRLFs, and returns a T-SQL expression suitable for INSERT or UPDATE operations. It's got some of our proprietary error handling in it, but once you rip that out, it may be helpful -- I hope so.

/// <summary>
/// Generate a SQL string value expression suitable for INSERT/UPDATE operations that prepends
/// the specified line to an existing block of text, assumed to have \r\n delimiters, and
/// truncate at a maximum length.
/// </summary>
/// <param name="sNewLine">Single text line to be prepended to existing text</param>
/// <param name="sOrigLines">Current text value; assumed to be CRLF-delimited</param>
/// <param name="iMaxLen">Integer field length</param>
/// <returns>String: SQL string expression suitable for INSERT/UPDATE operations.  Empty on error.</returns>
private string PrependCommentLine(string sNewLine, String sOrigLines, int iMaxLen)
{
    String fn = MethodBase.GetCurrentMethod().Name;

    try
    {
        String [] line_array = sOrigLines.Split("\r\n".ToCharArray());
        List<string> orig_lines = new List<string>();
        foreach(String orig_line in line_array) 
        { 
            if (!String.IsNullOrEmpty(orig_line))  
            {  
                orig_lines.Add(orig_line);    
            }
        } // end foreach(original line)

        String final_comments = "'" + sNewLine + "' + CHAR(13) + CHAR(10) ";
        int cum_length = sNewLine.Length + 2;
        foreach(String orig_line in orig_lines)
        {
            String curline = orig_line;
            if (cum_length >= iMaxLen) break;                // stop appending if we're already over
            if ((cum_length+orig_line.Length+2)>=iMaxLen)    // If this one will push us over, truncate and warn:
            {
                Util.HandleAppErr(this, fn, "Truncating comments: " + orig_line);
                curline = orig_line.Substring(0, iMaxLen - (cum_length + 3));
            }
            final_comments += " + '" + curline + "' + CHAR(13) + CHAR(10) \r\n";
            cum_length += orig_line.Length + 2;
        } // end foreach(second pass on original lines)

        return(final_comments);


    } // end main try()
    catch(Exception exc)
    {
        Util.HandleExc(this,fn,exc);
        return("");
    }
}

jQuery convert line breaks to br (nl2br equivalent)

I wrote a little jQuery extension for this:

$.fn.nl2brText = function (sText) {
    var bReturnValue = 'undefined' == typeof sText;
    if(bReturnValue) {
        sText = $('<pre>').html(this.html().replace(/<br[^>]*>/i, '\n')).text();
    }
    var aElms = [];
    sText.split(/\r\n|\r|\n/).forEach(function(sSubstring) {
        if(aElms.length) {
            aElms.push(document.createElement('br'));
        }
        aElms.push(document.createTextNode(sSubstring));
    });
    var $aElms = $(aElms);
    if(bReturnValue) {
        return $aElms;
    }
    return this.empty().append($aElms);
};

How do I create a new line in Javascript?

For a string I just write "\n" to give me a new line. For example, typing console.log("First Name: Rex" + "\n" + "Last Name: Blythe"); Will type:

First Name: Rex

Last Name: Blythe

How to add line break for UILabel?

Important to note it's \n (backslash) rather than /n.

Match linebreaks - \n or \r\n?

In PCRE \R matches \n, \r and \r\n.

How to break lines in PowerShell?

I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)

Thanks!

How can I put strings in an array, split by new line?

$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);

foreach ($arr as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

true array:

$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);

$array = array(); // inisiasi variable array in format array

foreach ($arr as $line) { // loop line by line and convert into array
    $array[] = $line;
};

print_r($array); // display all value

echo $array[1]; // diplay index 1

Embed Online:

_x000D_
_x000D_
body, html, iframe { _x000D_
  width: 100% ;_x000D_
  height: 100% ;_x000D_
  overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/vE1gst" ></iframe>
_x000D_
_x000D_
_x000D_

How to linebreak an svg text within javascript?

I suppese you alredy managed to solve it, but if someone is looking for similar solution then this worked for me:

 g.append('svg:text')
  .attr('x', 0)
  .attr('y', 30)
  .attr('class', 'id')
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 5)
  .text(function(d) { return d.name; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.sname; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.idcode; })

There are 3 lines separated with linebreak.

How do I format a String in an email so Outlook will print the line breaks?

Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.

This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.

For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:

Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543

Your Outlook recipient will see the information all smashed together, as follows:

Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543

There doesn't seem to be an easy solution. Alternatives are:

  1. You can supply two sets of line breaks between each line. That does stop Outlook from combining the lines onto one line, but it then displays an extra blank line between each line (creating the opposite problem). By "supply two sets of line breaks" I mean you should use "\r\n\r\n" or "\r\r" or "\n\n" but not "\r\n" or "\n\r".
  2. You can supply two spaces at the beginning of every line in the body of your email message. That avoids introducing an extra blank line between each line. But this works best if each line in your message is fairly short, because the user may be previewing the text in a very narrow Outlook window that wraps the end of each line around to the first position on the next line, where it won't line up with your two-space-indented lines. This strategy has been used for some newsletters.
  3. You can give up on using a plain text format, and use an html format.

Split string in JavaScript and detect line break

You should try detect the first line.

Then the:

if(n == 0){
  line = words[n]+"\n";
}

I'm not sure, but maybe it helps.

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

On Linux and Mac OS, the following works,

:%s/^V^M/^V^M/g

where ^V^M means type Ctrl+V, then Ctrl+M.

Note: on Windows you probably want to use ^Q instead of ^V, since by default ^V is mapped to paste text.

See line breaks and carriage returns in editor

You can view break lines using gedit editor.

First, if you don't have installed:

sudo apt-get install gedit

Now, install gedit plugins:

sudo apt-get install gedit-plugins

and select Draw Spaces plugin, enter on Preferences, and chose Draw new lines

enter image description here

enter image description here

Using VSCode you can install Line endings extension.

Sublime Text 3 has a plugin called RawLineEdit that will display line endings and allow the insertion of arbitrary line-ending type

shift + ctrl + p and start type the name of the plugin, and toggle to show line ending.

How to add a line break in an Android TextView?

As Html.fromHtml deprecated I simply I used this code to get String2 in next line.

textView.setText(fromHtml("String1 <br/> String2"));

.

@SuppressWarnings("deprecation")
    public static Spanned fromHtml(String html){
        Spanned result;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
        } else {
            result = Html.fromHtml(html);
        }
        return result;
    }

HTML5 tag for horizontal line break

Simply use hr tag in HTML file and add below code in CSS file .

    hr {
       display: block;
       position: relative;
       padding: 0;
       margin: 8px auto;
       height: 0;
       width: 100%;
       max-height: 0;
       font-size: 1px;
       line-height: 0;
       clear: both;
       border: none;
       border-top: 1px solid #aaaaaa;
       border-bottom: 1px solid #ffffff;
    }

it works perfectly .

How do I break a string across more than one line of code in JavaScript?

You can just use

1:  alert("Please select file" +
2:        " to delete");

That should work

Multiple lines of text in UILabel

Try using this:

lblName.numberOfLines = 0;
[lblName sizeToFit];

Can you target <br /> with css?

old question but this is a pretty neat and clean fix, might come in use for people who are still wondering if it's possible :):

_x000D_
_x000D_
br{_x000D_
    content: '.';_x000D_
    display: inline-block;_x000D_
    width: 100%;_x000D_
    border-bottom: 1px dashed black;_x000D_
}
_x000D_
_x000D_
_x000D_

with this fix you can also remove BRs on websites ( just set the width to 0px )

How to print a linebreak in a python function?

All three way you can use for newline character :

'\n'

"\n"

"""\n"""

Latex Multiple Linebreaks

\\\\

This works on pdfLatex. It creates 2 new lines for you.

Is it possible to break a long line to multiple lines in Python?

DB related code looks easier on the eyes in multiple lines, enclosed by a pair of triple quotes:

SQL = """SELECT
            id, 
            fld_1, 
            fld_2, 
            fld_3, 
            ...... 
         FROM some_tbl"""

than the following one giant long line:

SQL = "SELECT id, fld_1, fld_2, fld_3, .................................... FROM some_tbl"

What is the difference between a "line feed" and a "carriage return"?

Since I can not comment because of not having enough reward points I have to answer to correct answer given by @Burhan Khalid.
In very layman language Enter key press is combination of carriage return and line feed.
Carriage return points the cursor to the beginning of the line horizontly and Line feed shifts the cursor to the next line vertically.Combination of both gives you new line(\n) effect.
Reference - https://en.wikipedia.org/wiki/Carriage_return#Computers

adding line break

This worked for me:

foreach (var item in FirmNameList){
    if (FirmNames != "")
    {
        FirmNames += ",\r\n"
    }

    FirmNames += item;
}

How to insert newline in string literal?

string myText =
    @"<div class=""firstLine""></div>
      <div class=""secondLine""></div>
      <div class=""thirdLine""></div>";

that's not it:

string myText =
@"<div class=\"firstLine\"></div>
  <div class=\"secondLine\"></div>
  <div class=\"thirdLine\"></div>";

How to force a line break in a long word in a DIV?

Found that using the following worked across most major browsers (Chrome, IE, Safari iOS/OSX) except Firefox (v50.0.2) when using flexbox and relying on width: auto.

.your_element {
    word-wrap: break-word;   
    overflow-wrap: break-word;
    word-break: break-word;
}

Note: you may need to add browser vendor prefixes if you are not using an autoprefixer.

Another thing to watch out for is text using &nbsp; for spacing can cause line breaks mid-word.

Can CSS force a line break after each word in an element?

You can't target each word in CSS. However, with a bit of jQuery you probably could.

With jQuery you can wrap each word in a <span> and then CSS set span to display:block which would put it on its own line.

In theory of course :P

Elegant solution for line-breaks (PHP)

Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.

Example:<br />
$myoutput =  "After this sentence there is a line break.<b>.|..</b> Here is a new line.";<br />
$myoutput =  str_replace(".|..","&lt;br />",$myoutput);<br />

or

how about:<br />
$myoutput =  "After this sentence there is a line break.<b>E(*)3</b> Here is a new line.";<br />
$myoutput =  str_replace("E(*)3","&lt;br />",$myoutput);<br />

I call the first method "middle finger style" and the second "goatse style".

multiple prints on the same line in Python

print() has a built in parameter "end" that is by default set to "\n" Calling print("This is America") is actually calling print("This is America", end = "\n"). An easy way to do is to call print("This is America", end ="")

How do I specify new lines on Python, when writing on files?

\n - simple newline character insertion works:

# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."

# Output:
In [37]: print(test_line)

Hi!!!
 testing first line..
 testing second line..
 and third line.....

How to add a new line in textarea element?

You might want to use \n instead of /n.

How to read a file without newlines?

temp = open(filename,'r').read().splitlines()

line breaks in a textarea

You could use str_replace to replace the <br /> tags into end of line characters.

str_replace('<br />', PHP_EOL, $textarea);

Alternatively, you could save the data in the database without calling nl2br first. That way the line breaks would remain. When you display as HTML, call nl2br. An additional benefit of this approach is that it would require less storage space in your database as a line break is 1 character as opposed to "<br />" which is 6.

No line-break after a hyphen

Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character &#8288; on either side of your hyphen, or em dash, or any character.

So, like so:

&#8288;—&#8288;

This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.

Neatest way to remove linebreaks in Perl

Reading perlport I'd suggest something like

$line =~ s/\015?\012?$//;

to be safe for whatever platform you're on and whatever linefeed style you may be processing because what's in \r and \n may differ through different Perl flavours.

Bash: Strip trailing linebreak from output

If you want to remove only the last newline, pipe through:

sed -z '$ s/\n$//'

sed won't add a \0 to then end of the stream if the delimiter is set to NUL via -z, whereas to create a POSIX text file (defined to end in a \n), it will always output a final \n without -z.

Eg:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//'; echo tender
foo
bartender

And to prove no NUL added:

$ { echo foo; echo bar; } | sed -z '$ s/\n$//' | xxd
00000000: 666f 6f0a 6261 72                        foo.bar

To remove multiple trailing newlines, pipe through:

sed -Ez '$ s/\n+$//'

Difference between CR LF, LF and CR line break types?

CR - ASCII code 13

LF - ASCII code 10.

Theoretically CR returns cursor to the first position (on the left). LF feeds one line moving cursor one line down. This is how in old days you controled printers and text-mode monitors. These characters are usually used to mark end of lines in text files. Different operating systems used different conventions. As you pointed out Windows uses CR/LF combination while pre-OSX Macs use just CR and so on.

How can I replace newline or \r\n with <br/>?

Try this:

echo str_replace(array('\r\n', '\n\r', '\n', '\r'), '<br>', $description);

Code line wrapping - how to handle long lines

Uses Guava's static factory methods for Maps and is only 105 characters long.

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper = Maps.newHashMap();

How can I do a line break (line continuation) in Python?

From the horse's mouth: Explicit line joining

Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:

if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1

A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

How to add line breaks to an HTML textarea?

I have a textarea with id is #infoartist follow:

<textarea id="infoartist" ng-show="dForm" style="width: 100%;" placeholder="Tell your contacts and collectors about yourself."></textarea>

In javascript code, i'll get value of textarea and replace escaping new line (\n\r) by <br /> tag, such as:

var text = document.getElementById("infoartist").value;
text = text.replace(/\r?\n/g, '<br />');

So if you are using jquery (like me):

var text = $("#infoartist").val();
text = text.replace(/\r?\n/g, '<br />');

Hope it helped you. :-)

Render a string in HTML and preserve spaces and linebreaks

There is a simple way to do it. I tried it on my app and it worked pretty well.

Just type: $text = $row["text"]; echo nl2br($text);

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

Another situation is to check that the Primary Key is the same name as with your classes where the only difference is that your primary key has an 'ID' appended to it or to specify [Key] on primary keys that are not related to how the class is named.

JavaScript: undefined !== undefined?

I'd like to post some important information about undefined, which beginners might not know.

Look at the following code:

 /* 
  * Consider there is no code above. 
  * The browser runs these lines only.
  */

   // var a;  
   // --- commented out to point that we've forgotten to declare `a` variable 

   if ( a === undefined ) {
       alert('Not defined');
   } else {
       alert('Defined: ' + a);
   }

   alert('Doing important job below');

If you run this code, where variable a HAS NEVER BEEN DECLARED using var, you will get an ERROR EXCEPTION and surprisingly see no alerts at all.

Instead of 'Doing important job below', your script will TERMINATE UNEXPECTEDLY, throwing unhandled exception on the very first line.


Here is the only bulletproof way to check for undefined using typeof keyword, which was designed just for such purpose:

   /* 
    * Correct and safe way of checking for `undefined`: 
    */

   if ( typeof a === 'undefined' ) {
       alert(
           'The variable is not declared in this scope, \n' +
           'or you are pointing to unexisting property, \n' +
           'or no value has been set yet to the variable, \n' + 
           'or the value set was `undefined`. \n' +
           '(two last cases are equivalent, don\'t worry if it blows out your mind.'
           );
   }

   /* 
    *  Use `typeof` for checking things like that
    */

This method works in all possible cases.

The last argument to use it is that undefined can be potentially overwritten in earlier versions of Javascript:

     /* @ Trollface @ */
        undefined = 2;
     /* Happy debuging! */  

Hope I was clear enough.

How do I get the XML root node with C#?

I got the same question here. If the document is huge, it is not a good idea to use XmlDocument. The fact is that the first element is the root element, based on which XmlReader can be used to get the root element. Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.

  using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
    while (reader.Read()) {
      // first element is the root element
      if (reader.NodeType == XmlNodeType.Element) {
        System.Console.WriteLine(reader.Name);
        break;
      }
    }
  }

How to download and save an image in Android

this code perfectly run in my project

downloadImagesToSdCard(imagepath,imagepath);

private void downloadImagesToSdCard(String downloadUrl,String imageName)
        {
            try
            {
                URL url = new URL("www.xxx.com"+downloadUrl); 
                /* making a directory in sdcard */
            //  String sdCard=Environment.getExternalStorageDirectory().toString();
                ContextWrapper cw = new ContextWrapper(getActivity());
                 // path to /data/data/yourapp/app_data/imageDir
                File directory = cw.getDir("files", Context.MODE_PRIVATE);

                File myDir = new File(directory,"folder");

                /*  if specified not exist create new */
                if(!myDir.exists())
                {
                    myDir.mkdir();
                    Log.v("", "inside mkdir");
                }

                /* checks the file and if it already exist delete */
                String fname = imageName;
                File file = new File (myDir, fname);
                Log.d("file===========path", ""+file);
                if (file.exists ()) 
                    file.delete (); 

                /* Open a connection */
                URLConnection ucon = url.openConnection();
                InputStream inputStream = null;
                HttpURLConnection httpConn = (HttpURLConnection)ucon;
                httpConn.setRequestMethod("GET");
                httpConn.connect();
                inputStream = httpConn.getInputStream();
                /*if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) 
                {
                    inputStream = httpConn.getInputStream();
                }*/

                FileOutputStream fos = new FileOutputStream(file);  
                int totalSize = httpConn.getContentLength();
                int downloadedSize = 0;   
                byte[] buffer = new byte[1024];
                int bufferLength = 0;
                while ( (bufferLength = inputStream.read(buffer)) >0 ) 
                {                 
                    fos.write(buffer, 0, bufferLength);                  
                    downloadedSize += bufferLength;                 
                    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
                }   

                fos.close();
                Log.d("test", "Image Saved in sdcard..");  
                viewimage();
            }
            catch(IOException io)
            {                  
                io.printStackTrace();
            }
            catch(Exception e)
            {                     
                e.printStackTrace();
            }


        } 

        public void viewimage()
        {
              String path = serialnumber+".png";
               ContextWrapper cw = new ContextWrapper(getActivity());

                //path to /data/data/yourapp/app_data/dirName
                File directory = cw.getDir("files", Context.MODE_PRIVATE);

                File mypath=new File(directory,"folder/"+path);

                Bitmap b;
                try {
                    b = BitmapFactory.decodeStream(new FileInputStream(mypath));
                //  b.compress(format, quality, stream)
                    profile_image.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }

Where can I find jenkins restful api reference?

Additional Solution: use Restul api wrapper libraries written in Java / python / Ruby - An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.

For documentation and links: Remote Access API

How to force a line break in a long word in a DIV?

&#8203; is the HTML entity for a unicode character called the zero-width space (ZWSP) which is an invisible character which specifies a line-break opportunity. Similarly the hyphen's purpose is to specify a line-break opportunity within a word boundary.

How to align two elements on the same line without changing HTML

By using display: inline-block; And more generally when you have a parent (always there is a parent except for html) use display: inline-block; for the inner elements. and to force them to stay in the same line even when the window get shrunk (contracted). Add for the parent the two property:

    white-space: nowrap;
    overflow-x: auto;

here a more formatted example to make it clear:

.parent {
    white-space: nowrap;
    overflow-x: auto;
}

.children {
   display: inline-block;
   margin-left: 20px; 
}

For this example particularly, you can apply the above as fellow (i'm supposing the parent is body. if not you put the right parent), you can also like change the html and add a parent for them if it's possible.

body { /*body may pose problem depend on you context, there is no better then have a specific parent*/
        white-space: nowrap;
        overflow-x: auto;
 }

#element1, #element2{ /*you can like put each one separately, if the margin for the first element is not wanted*/
   display: inline-block;
   margin-left: 10px; 
}

keep in mind that white-space: nowrap; and overlow-x: auto; is what you need to force them to be in one line. white-space: nowrap; disable wrapping. And overlow-x:auto; to activate scrolling, when the element get over the frame limit.

How to implement class constants?

All of the replies with readonly are only suitable when this is a pure TS environment - if it's ever being made into a library then this doesn't actually prevent anything, it just provides warnings for the TS compiler itself.

Static is also not correct - that's adding a method to the Class, not to an instance of the class - so you need to address it directly.

There are several ways to manage this, but the pure TS way is to use a getter - exactly as you have done already.

The alternative way is to put it in as readonly, but then use Object.defineProperty to lock it - this is almost the same thing that is being done via the getter, but you can lock it to have a value, rather than a method to use to get it -

class MyClass {
    MY_CONSTANT = 10;

    constructor() {
        Object.defineProperty(this, "MY_CONSTANT", {value: this.MY_CONSTANT});
    }
}

The defaults make it read-only, but check out the docs for more details.

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Simulating ENTER keypress in bash script

You could make use of expect (man expect comes with examples).

Mock a constructor with parameter

Mockito has limitations testing final, static, and private methods.

with jMockit testing library, you can do few stuff very easy and straight-forward as below:

Mock constructor of a java.io.File class:

new MockUp<File>(){
    @Mock
    public void $init(String pathname){
        System.out.println(pathname);
        // or do whatever you want
    }
};
  • the public constructor name should be replaced with $init
  • arguments and exceptions thrown remains same
  • return type should be defined as void

Mock a static method:

  • remove static from the method mock signature
  • method signature remains same otherwise

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

Found a solution that works for me looking here (see the third comment on the first answer). This code looks for a valid twitter client and uses it to post the tweet. Note: It does not give you an Intent with the various Twitter clients and allow you to choose.

Share using twitter:

Intent shareIntent = findTwitterClient(); 
shareIntent.putExtra(Intent.EXTRA_TEXT, "test");
startActivity(Intent.createChooser(shareIntent, "Share"));

Calling this method:

public Intent findTwitterClient() {
    final String[] twitterApps = {
            // package // name - nb installs (thousands)
            "com.twitter.android", // official - 10 000
            "com.twidroid", // twidroid - 5 000
            "com.handmark.tweetcaster", // Tweecaster - 5 000
            "com.thedeck.android" }; // TweetDeck - 5 000 };
    Intent tweetIntent = new Intent();
    tweetIntent.setType("text/plain");
    final PackageManager packageManager = getPackageManager();
    List<ResolveInfo> list = packageManager.queryIntentActivities(
            tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);

    for (int i = 0; i < twitterApps.length; i++) {
        for (ResolveInfo resolveInfo : list) {
            String p = resolveInfo.activityInfo.packageName;
            if (p != null && p.startsWith(twitterApps[i])) {
                tweetIntent.setPackage(p);
                return tweetIntent;
            }
        }
    }

    return null;
}

Facebook will be similar using "com.facebook.katana", although you still can't set the message text (deprecated July 2011).

Code source: Intent to open twitter client on Android

Failed to connect to camera service

I came up with the same problem and I'm sharing how I fixed it. It may help some people.

First, check your Android version. If it is running on Android 6.0 and higher (API level 23+), then you need to :

  1. Declare a permission in the app manifest. Make sure to insert the permission above the application tag.

**<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />**

<application ...>
    ...
</application>

  1. Then, request that the user approve each permission at runtime

      if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
        != PackageManager.PERMISSION_GRANTED) {
    // here, Permission is not granted
    ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA}, 50);
    }
    

For more information, have a look at the API documentation here

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Check if any ancestor has a class using jQuery

You can use parents method with specified .class selector and check if any of them matches it:

if ($elem.parents('.left').length != 0) {
    //someone has this class
}

Initializing a two dimensional std::vector

I think the easiest way to make it done is :

std::vector<std::vector<int>>v(10,std::vector<int>(11,100));

10 is the size of the outer or global vector, which is the main one, and 11 is the size of inner vector of type int, and initial values are initialized to 100! That's my first help on stack, i think it helps someone.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

In our case, the reason was invalid header. As mentioned in Edit 4:

  • take the logs
  • in the viewer choose Events
  • chose HTTP2_SESSION

Look for something similar:

HTTP2_SESSION_RECV_INVALID_HEADER

--> error = "Invalid character in header name."

--> header_name = "charset=utf-8"

How can you flush a write using a file descriptor?

If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :

                                                          FDOPEN(P)

NAME

       fdopen - associate a stream with a file descriptor

SYNOPSIS

       #include <stdio.h>

       FILE *fdopen(int fildes, const char *mode);

Where can I find the .apk file on my device, when I download any app and install?

You can do that I believe. It needs root permission. If you want to know where your apk files are stored, open a emulator and then go to

DDMS>File Explorer-> you can see a directory by name "data" -> Click on it and you will see a "app" folder.

Your apks are stored there. In fact just copying a apk directly to the folder works for me with emulators.

Change table header color using bootstrap

Try This:

table.table tr th{background-color:blue !important; font-color:white !important;}

hope this helps..

How to use a switch case 'or' in PHP

switch ($value) 
{
   case 1:
   case 2:
      echo 'the value is either 1 or 2';
   break;
}

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

Whenever such an error occurs. Try to check Following Things

  1. Check what kind of Activity is being used, is it a simple android.app Activity or an AppCompatActivity or an ActionBarActivity and so on.

  2. Check if your activity type which is extended falls under the compat category

example android.app based Activity/Fragment are non appCompat types, whereas android.support.v4.app.Fragment or android.support.v4.app.ActivityCompat are appCompat based

if it falls under appCompat we use getSupportActionBar() else for android.app types we can use getActionBar()

  1. Check the theme applied to the activity in question in the manifest file

example: In the manifest file if theme applied is say android:theme="@android:style/Theme.Holo.Dialog" getActionBar() will work

but if theme applied for the activity in the manifest is as follows android:theme="@style/Theme.AppCompat.Light" then you have to use getSupportActionBar()

How do I work with dynamic multi-dimensional arrays in C?

Since C99, C has 2D arrays with dynamical bounds. If you want to avoid that such beast are allocated on the stack (which you should), you can allocate them easily in one go as the following

double (*A)[n] = malloc(sizeof(double[n][n]));

and that's it. You can then easily use it as you are used for 2D arrays with something like A[i][j]. And don't forget that one at the end

free(A);

Randy Meyers wrote series of articles explaining variable length arrays (VLAs).

"Find next" in Vim

If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.

Angular 2 'component' is not a known element

I am beginning Angular and in my case, the issue was that I hadn't saved the file after adding the 'import' statement.

The identity used to sign the executable is no longer valid

I selected None from Team dropdown in target general settings. Then selected the original team. Xcode shows some spinner next to it. Wait for it to complete and then everything works. Tried it in Xcode 6.2

Is there a php echo/print equivalent in javascript

this is an another way:

<html>
<head>
    <title>Echo</title>
    <style type="text/css">
    #result{
        border: 1px solid #000000;
        min-height: 250px;
        max-height: 100%;
        padding: 5px;
        font-family: sans-serif;
        font-size: 12px;
    }
    </style>
    <script type="text/javascript" lang="ja">
    function start(){
        function echo(text){
            lastResultAreaText = document.getElementById('result').innerHTML;
            resultArea = document.getElementById('result');
            if(lastResultAreaText==""){
                resultArea.innerHTML=text;
            }
            else{
                resultArea.innerHTML=lastResultAreaText+"</br>"+text;
            }
        }

        echo("Hello World!");
        }
    </script>
</head>
<body onload="start()">
<pre id="result"></pre> 
</body>

C# Dictionary get item by index

Is it useful to look beyond the exact question asked to alternatives that might better suit the need? Create your own class or struct, then make an array of those to operate on instead of being stuck with the operation of the KeyValuePair collection behavior of the Dictionary type.

Using a struct instead of a class will allow equality comparison of two different cards without implementing your own comparison code.

public struct Card
{
  public string Name;
  public int Value;

}

private int random()
{
  // Whatever
  return 1;
}

private static Card[] Cards = new Card[]
{
    new Card() { Name = "7", Value = 7 },
    new Card() { Name = "8", Value = 8 },
    new Card() { Name = "9", Value = 9 },
    new Card() { Name = "10", Value = 10 },
    new Card() { Name = "J", Value = 1 },
    new Card() { Name = "Q", Value = 1 },
    new Card() { Name = "K", Value = 1 },
    new Card() { Name = "A", Value = 1 }
};

private void CardDemo()
{
  int value, maxVal;
  string name;
  Card card, card2;
  List<Card> lowCards;

  value = Cards[random()].Value;
  name = Cards[random()].Name;
  card = Cards[random()];
  card2 = Cards[1];
  // card.Equals(card2) returns true
  lowCards = Cards.Where(x => x.Value == 1).ToList();
  maxVal = Cards.Max(x => x.Value);

}

Remove Identity from a column in a table

In SQL Server you can turn on and off identity insert like this:

SET IDENTITY_INSERT table_name ON

-- run your queries here

SET IDENTITY_INSERT table_name OFF

Using @property versus getters and setters

I am surprised that nobody has mentioned that properties are bound methods of a descriptor class, Adam Donohue and NeilenMarais get at exactly this idea in their posts -- that getters and setters are functions and can be used to:

  • validate
  • alter data
  • duck type (coerce type to another type)

This presents a smart way to hide implementation details and code cruft like regular expression, type casts, try .. except blocks, assertions or computed values.

In general doing CRUD on an object may often be fairly mundane but consider the example of data that will be persisted to a relational database. ORM's can hide implementation details of particular SQL vernaculars in the methods bound to fget, fset, fdel defined in a property class that will manage the awful if .. elif .. else ladders that are so ugly in OO code -- exposing the simple and elegant self.variable = something and obviate the details for the developer using the ORM.

If one thinks of properties only as some dreary vestige of a Bondage and Discipline language (i.e. Java) they are missing the point of descriptors.

new Image(), how to know if image 100% loaded or not?

Use the load event:

img = new Image();

img.onload = function(){
  // image  has been loaded
};

img.src = image_url;

Also have a look at:

finding first day of the month in python

This is a pithy solution.

import datetime 

todayDate = datetime.date.today()
if todayDate.day > 25:
    todayDate += datetime.timedelta(7)
print todayDate.replace(day=1)

One thing to note with the original code example is that using timedelta(30) will cause trouble if you are testing the last day of January. That is why I am using a 7-day delta.

How to calculate the angle between a line and the horizontal axis?

Sorry, but I'm pretty sure Peter's answer is wrong. Note that the y axis goes down the page (common in graphics). As such the deltaY calculation has to be reversed, or you get the wrong answer.

Consider:

System.out.println (Math.toDegrees(Math.atan2(1,1)));
System.out.println (Math.toDegrees(Math.atan2(-1,1)));
System.out.println (Math.toDegrees(Math.atan2(1,-1)));
System.out.println (Math.toDegrees(Math.atan2(-1,-1)));

gives

45.0
-45.0
135.0
-135.0

So if in the example above, P1 is (1,1) and P2 is (2,2) [because Y increases down the page], the code above will give 45.0 degrees for the example shown, which is wrong. Change the order of the deltaY calculation and it works properly.

setInterval in a React app

I see 4 issues with your code:

  • In your timer method you are always setting your current count to 10
  • You try to update the state in render method
  • You do not use setState method to actually change the state
  • You are not storing your intervalId in the state

Let's try to fix that:

componentDidMount: function() {
   var intervalId = setInterval(this.timer, 1000);
   // store intervalId in the state so it can be accessed later:
   this.setState({intervalId: intervalId});
},

componentWillUnmount: function() {
   // use intervalId from the state to clear the interval
   clearInterval(this.state.intervalId);
},

timer: function() {
   // setState method is used to update the state
   this.setState({ currentCount: this.state.currentCount -1 });
},

render: function() {
    // You do not need to decrease the value here
    return (
      <section>
       {this.state.currentCount}
      </section>
    );
}

This would result in a timer that decreases from 10 to -N. If you want timer that decreases to 0, you can use slightly modified version:

timer: function() {
   var newCount = this.state.currentCount - 1;
   if(newCount >= 0) { 
       this.setState({ currentCount: newCount });
   } else {
       clearInterval(this.state.intervalId);
   }
},

Get generic type of class at runtime

Here is working solution!!!

@SuppressWarnings("unchecked")
    private Class<T> getGenericTypeClass() {
        try {
            String className = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
            Class<?> clazz = Class.forName(className);
            return (Class<T>) clazz;
        } catch (Exception e) {
            throw new IllegalStateException("Class is not parametrized with generic type!!! Please use extends <> ");
        }
    } 

NOTES: Can be used only as superclass
1. Has to be extended with typed class (Child extends Generic<Integer>)
OR

2. Has to be created as anonymous implementation (new Generic<Integer>() {};)

What is the easiest way to push an element to the beginning of the array?

You can use methodsolver to find Ruby functions.

Here is a small script,

require 'methodsolver'

solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }

Running this prints

Found 1 methods
- Array#unshift

You can install methodsolver using

gem install methodsolver

How to hide columns in HTML table?

You can use the nth-child CSS selector to hide a whole column:

#myTable tr > *:nth-child(2) {
    display: none;
}

This works under assumption that a cell of column N (be it a th or td) is always the Nth child element of its row.

Here's a demo.


? If you want the column number to be dynamic, you could do that using querySelectorAll or any framework presenting similar functionality, like jQuery here:

$('#myTable tr > *:nth-child(2)').hide();

Demo with jQuery

(The jQuery solution also works on legacy browsers that don't support nth-child).

C# "internal" access modifier when doing unit testing

Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.

Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.

One thing to consider might be a "ForTest" suffix:

internal void DoThisForTest(string name)
{
    DoThis(name);
}

private void DoThis(string name)
{
    // Real implementation
}

Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.

Download TS files from video stream

  • Get one Link from Network tab of developer tools
  • Remove index and ts extension from link

With following script you can save movie to Videos folder

Example usage:

download-video.sh https://url.com/video.mp4 video-name

download-video.sh

#!/bin/bash
LINK=$1
NAME=$2

START=0
END=2000

help()
{
    echo "download-video.sh <url> <output-name>"
    echo "<url>: x.mp4 (without .ts)"
    echo "<output-name>: x (without .mp4)"
} 

create_folders()
{
    # create folder for streaming media
    cd ~/Videos
    mkdir download-videos
    cd download-videos
}

print_variables()
{
    echo "Execute Download with following parameters"
    echo "Link $LINK"
    echo "Name $NAME"
}

check_video()
{
    i=$START
    while [[ $i -le $END ]]
    do
        URL=$LINK'-'$i.ts
        STATUS_CODE=$(curl -o /dev/null --silent --head --write-out '%{http_code}\n' $URL)
        if [ "$STATUS_CODE" == "200" ]; then
            break
        fi
        ((i = i + 1))
    done

    if [ "$STATUS_CODE" == "200" ]; then
        START=$i
        echo "START is $START"
    else 
        echo "File not found"
    fi
} 


download_video()
{
    i=$START
    e=$END
    while [[ $i -le $END ]]
    do
        URL=$LINK'-'$i.ts
        STATUS_CODE=$(curl -o /dev/null --silent --head --write-out '%{http_code}\n' $URL)
        if [ "$STATUS_CODE" != "200" ]; then
            break
        fi
        wget $URL
        e=$i
        ((i = i + 1))
    done

    END=$e
}

concat_videos()
{
    DIR="${LINK##*/}"

    i=$START
    echo "i is $i"
    while [[ $i -le $END ]]
    do
        FILE=$DIR'-'$i.ts
        echo $FILE | tr " " "\n" >> tslist
        ((i = i + 1))
    done
    while read line; 
    do 
        echo "gugu"$line
        cat $line >> $NAME.mp4; 
    done < tslist

    rm *.ts tslist
}

if [ "$1" == "" ]; then
    echo "No video url provided"
    help
else
    LINK=$1
    if [ "$2" == "" ]; then
        echo "No video output-name provided"
        help
    else
        NAME=$2
        create_folders
        print_variables
        check_video
        download_video
        concat_videos
    fi
fi

"ImportError: no module named 'requests'" after installing with pip

Run in command prompt.

pip list

Check what version you have installed on your system if you have an old version.

Try to uninstall the package...

pip uninstall requests

Try after to install it:

pip install requests

You can also test if pip does not do the job.

easy_install requests

Relative imports for the billionth time

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Wrote a little python package to PyPi that might help viewers of this question. The package acts as workaround if one wishes to be able to run python files containing imports containing upper level packages from within a package / project without being directly in the importing file's directory. https://pypi.org/project/import-anywhere/

SVN remains in conflict?

I had the same issue on linux, but I couldn't fix it with the accepted answer. I was able to solve it by using cd to go to the correct folder and then executing:

svn remove --force filename  
syn resolve --accept=working filename  
svn up

That's all.

How get all values in a column using PHP?

PHP 5 >= 5.5.0, PHP 7

Use array_column on the result array

$column = array_column($result, 'names');

Embedding Base64 Images

Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.

I reccomend you to use the following tools for online base64 encoding/decoding:

Check the "Format as Data URL" option to format as a Data URL.

Common Header / Footer with static HTML

The best solution is using a static site generator which has templating/includes support. I use Hammer for Mac, it is great. There's also Guard, a ruby gem that monitors file changes, compile sass, concatenate any files and probably does includes.

Make a VStack fill the width of the screen in SwiftUI

There is a better way!

To make the VStack fill the width of it's parent you can use a GeometryReader and set the frame. (.relativeWidth(1.0) should work but apparently doesn't right now)

struct ContentView : View {
    var body: some View {
        GeometryReader { geometry in
            VStack {
                Text("test")
            }
                .frame(width: geometry.size.width,
                       height: nil,
                       alignment: .topLeading)
        }
    }
}

To make the VStack the width of the actual screen you can use UIScreen.main.bounds.width when setting the frame instead of using a GeometryReader, but I imagine you likely wanted the width of the parent view.

Also, this way has the added benefit of not adding spacing in your VStack which might happen (if you have spacing) if you added an HStack with a Spacer() as it's content to the VStack.

UPDATE - THERE IS NOT A BETTER WAY!

After checking out the accepted answer, I realized that the accepted answer doesn't actually work! It appears to work at first glance, but if you update the VStack to have a green background you'll notice the VStack is still the same width.

struct ContentView : View {
    var body: some View {
        NavigationView {
            VStack(alignment: .leading) {
                Text("Hello World")
                    .font(.title)
                Text("Another")
                    .font(.body)
                Spacer()
                }
                .background(Color.green)
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
                .background(Color.red)
        }
    }
}

This is because .frame(...) is actually adding another view to the view hierarchy and that view ends up filling the screen. However, the VStack still does not.

This issue also seems to be the same in my answer as well and can be checked using the same approach as above (putting different background colors before and after the .frame(...). The only way that appears to actually widen the VStack is to use spacers:

struct ContentView : View {
    var body: some View {
        VStack(alignment: .leading) {
            HStack{
                Text("Title")
                    .font(.title)
                Spacer()
            }
            Text("Content")
                .lineLimit(nil)
                .font(.body)
            Spacer()
        }
            .background(Color.green)
    }
}

Simulating Button click in javascript

Or you can use what JQuery alreay made for you:

http://jqueryui.com/datepicker/#icon-trigger

It's what you are trying to achieve isn't it?

Using Helvetica Neue in a Website

Assuming you have referenced and correctly integrated your font to your site (presumably using an @font-face kit) it should be alright to just reference yours the way you do. Presumably it is like this so they have fall backs incase some browsers do not render the fonts correctly

Using Java with Nvidia GPUs (CUDA)

There is not much information on the nature of the problem and the data, so difficult to advise. However, would recommend to assess the feasibility of other solutions, that can be easier to integrate with java and enables horizontal as well as vertical scaling. The first I would suggest to look at is an open source analytical engine called Apache Spark https://spark.apache.org/ that is available on Microsoft Azure but probably on other cloud IaaS providers too. If you stick to involving your GPU then the suggestion is to look at other GPU supported analytical databases on the market that fits in the budget of your organisation.

Should MySQL have its timezone set to UTC?

It seems that it does not matter what timezone is on the server as long as you have the time set right for the current timezone, know the timezone of the datetime columns that you store, and are aware of the issues with daylight savings time.

On the other hand if you have control of the timezones of the servers you work with then you can have everything set to UTC internally and never worry about timezones and DST.

Here are some notes I collected of how to work with timezones as a form of cheatsheet for myself and others which might influence what timezone the person will choose for his/her server and how he/she will store date and time.

MySQL Timezone Cheatsheet

Notes:

  1. Changing the timezone will not change the stored datetime or timestamp, but it will select a different datetime from timestamp columns
  2. Warning! UTC has leap seconds, these look like '2012-06-30 23:59:60' and can be added randomly, with 6 months prior notice, due to the slowing of the earths rotation
  3. GMT confuses seconds, which is why UTC was invented.

  4. Warning! different regional timezones might produce the same datetime value due to daylight savings time

  5. The timestamp column only supports dates 1970-01-01 00:00:01 to 2038-01-19 03:14:07 UTC, due to a limitation.
  6. Internally a MySQL timestamp column is stored as UTC but when selecting a date MySQL will automatically convert it to the current session timezone.

    When storing a date in a timestamp, MySQL will assume that the date is in the current session timezone and convert it to UTC for storage.

  7. MySQL can store partial dates in datetime columns, these look like "2013-00-00 04:00:00"
  8. MySQL stores "0000-00-00 00:00:00" if you set a datetime column as NULL, unless you specifically set the column to allow null when you create it.
  9. Read this

To select a timestamp column in UTC format

no matter what timezone the current MySQL session is in:

SELECT 
CONVERT_TZ(`timestamp_field`, @@session.time_zone, '+00:00') AS `utc_datetime` 
FROM `table_name`

You can also set the sever or global or current session timezone to UTC and then select the timestamp like so:

SELECT `timestamp_field` FROM `table_name`

To select the current datetime in UTC:

SELECT UTC_TIMESTAMP();
SELECT UTC_TIMESTAMP;
SELECT CONVERT_TZ(NOW(), @@session.time_zone, '+00:00');

Example result: 2015-03-24 17:02:41

To select the current datetime in the session timezone

SELECT NOW();
SELECT CURRENT_TIMESTAMP;
SELECT CURRENT_TIMESTAMP();

To select the timezone that was set when the server launched

SELECT @@system_time_zone;

Returns "MSK" or "+04:00" for Moscow time for example, there is (or was) a MySQL bug where if set to a numerical offset it would not adjust the Daylight savings time

To get the current timezone

SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);

It will return 02:00:00 if your timezone is +2:00.

To get the current UNIX timestamp (in seconds):

SELECT UNIX_TIMESTAMP(NOW());
SELECT UNIX_TIMESTAMP();

To get the timestamp column as a UNIX timestamp

SELECT UNIX_TIMESTAMP(`timestamp`) FROM `table_name`

To get a UTC datetime column as a UNIX timestamp

SELECT UNIX_TIMESTAMP(CONVERT_TZ(`utc_datetime`, '+00:00', @@session.time_zone)) FROM `table_name`

Get a current timezone datetime from a positive UNIX timestamp integer

SELECT FROM_UNIXTIME(`unix_timestamp_int`) FROM `table_name`

Get a UTC datetime from a UNIX timestamp

SELECT CONVERT_TZ(FROM_UNIXTIME(`unix_timestamp_int`), @@session.time_zone, '+00:00') 
FROM `table_name`

Get a current timezone datetime from a negative UNIX timestamp integer

SELECT DATE_ADD('1970-01-01 00:00:00',INTERVAL -957632400 SECOND) 

There are 3 places where the timezone might be set in MySQL:

Note: A timezone can be set in 2 formats:

  1. an offset from UTC: '+00:00', '+10:00' or '-6:00'
  2. as a named time zone: 'Europe/Helsinki', 'US/Eastern', or 'MET'

Named time zones can be used only if the time zone information tables in the mysql database have been created and populated.

in the file "my.cnf"

default_time_zone='+00:00'

or

timezone='UTC'

@@global.time_zone variable

To see what value they are set to

SELECT @@global.time_zone;

To set a value for it use either one:

SET GLOBAL time_zone = '+8:00';
SET GLOBAL time_zone = 'Europe/Helsinki';
SET @@global.time_zone='+00:00';

@@session.time_zone variable

SELECT @@session.time_zone;

To set it use either one:

SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
SET @@session.time_zone = "+00:00";

both "@@global.time_zone variable" and "@@session.time_zone variable" might return "SYSTEM" which means that they use the timezone set in "my.cnf".

For timezone names to work (even for default-time-zone) you must setup your timezone information tables need to be populated: http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html

Note: you can not do this as it will return NULL:

SELECT 
CONVERT_TZ(`timestamp_field`, TIMEDIFF(NOW(), UTC_TIMESTAMP), '+00:00') AS `utc_datetime` 
FROM `table_name`

Setup mysql timezone tables

For CONVERT_TZ to work, you need the timezone tables to be populated

SELECT * FROM mysql.`time_zone` ;
SELECT * FROM mysql.`time_zone_leap_second` ;
SELECT * FROM mysql.`time_zone_name` ;
SELECT * FROM mysql.`time_zone_transition` ;
SELECT * FROM mysql.`time_zone_transition_type` ;

If they are empty, then fill them up by running this command

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

if this command gives you the error "data too long for column 'abbreviation' at row 1", then it might be caused by a NULL character being appended at the end of the timezone abbreviation

the fix being to run this

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
(if the above gives error "data too long for column 'abbreviation' at row 1")
mysql_tzinfo_to_sql /usr/share/zoneinfo > /tmp/zut.sql

echo "SET SESSION SQL_MODE = '';" > /tmp/mysql_tzinfo_to.sql
cat /tmp/zut.sql >> /tmp/mysql_tzinfo_to.sql

mysql --defaults-file=/etc/mysql/my.cnf --user=verifiedscratch -p mysql < /tmp/mysql_tzinfo_to.sql

(make sure your servers dst rules are up to date zdump -v Europe/Moscow | grep 2011 https://chrisjean.com/updating-daylight-saving-time-on-linux/)

See the full DST (Daylight Saving Time) transition history for every timezone

SELECT 
tzn.Name AS tz_name,
tztt.Abbreviation AS tz_abbr,
tztt.Is_DST AS is_dst,
tztt.`Offset` AS `offset`,
DATE_ADD('1970-01-01 00:00:00',INTERVAL tzt.Transition_time SECOND)  AS transition_date
FROM mysql.`time_zone_transition` tzt
INNER JOIN mysql.`time_zone_transition_type` tztt USING(Time_zone_id, Transition_type_id)
INNER JOIN mysql.`time_zone_name` tzn USING(Time_zone_id)
-- WHERE tzn.Name LIKE 'Europe/Moscow' -- Moscow has weird DST changes
ORDER BY tzt.Transition_time ASC

CONVERT_TZ also applies any necessary DST changes based on the rules in the above tables and the date that you use.

Note:
According to the docs, the value you set for time_zone does not change, if you set it as "+01:00" for example, then the time_zone will be set as an offset from UTC, which does not follow DST, so it will stay the same all year round.

Only the named timezones will change time during daylight savings time.

Abbreviations like CET will always be a winter time and CEST will be summer time while +01:00 will always be UTC time + 1 hour and both won't change with DST.

The system timezone will be the timezone of the host machine where mysql is installed (unless mysql fails to determine it)

You can read more about working with DST here

related questions:

Sources:

Magento Product Attribute Get Value

This one works-

echo $_product->getData('ATTRIBUTE_NAME_HERE');

Enter key press behaves like a Tab in Javascript

I had a simular need. Here is what I did:

  <script type="text/javascript" language="javascript">
    function convertEnterToTab() {
      if(event.keyCode==13) {
        event.keyCode = 9;
      }
    }
    document.onkeydown = convertEnterToTab;    
  </script>  

TypeScript getting error TS2304: cannot find name ' require'

You can

declare var require: any

Or, for more comprehensive support, use DefinitelyTyped's require.d.ts

Also, instead of var mongoose = require('mongoose'), you could try the following

import mongoose from 'mongoose' // or
import mongoose = require('mongoose')

Best way to simulate "group by" from bash?

cat ip_addresses | sort | uniq -c | sort -nr | awk '{print $2 " " $1}'

this command would give you desired output

Exception.Message vs Exception.ToString()

Well, I'd say it depends what you want to see in the logs, doesn't it? If you're happy with what ex.Message provides, use that. Otherwise, use ex.toString() or even log the stack trace.

-didSelectRowAtIndexPath: not being called

I have had the same problem. And it was hard to find. But somewhere in my code was this:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    return nil;
}

It must be return indexPath, else -tableView:didSelectRowAtIndexPath: is not being called.

Make Https call using HttpClient

Add the below declarations to your class:

public const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
public const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;

After:

var client = new HttpClient();

And:

ServicePointManager.SecurityProtocol = Tls12;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 /*| SecurityProtocolType.Tls */| Tls12;

Happy? :)

“Unable to find manifest signing certificate in the certificate store” - even when add new key

Go to your project's "Properties" within visual studio. Then go to signing tab.

Then make sure Sign the Click Once manifests is turned off.


Updated Instructions:

Within your Solution Explorer:

  1. right click on your project
  2. click on properties
  3. usually on the left-hand side, select the "Signing" tab
  4. check off the Sign the ClickOnce manifests
  5. Make sure you save!

enter image description here

Oracle: If Table Exists

Another method is to define an exception and then only catch that exception letting all others propagate.

Declare
   eTableDoesNotExist Exception;
   PRAGMA EXCEPTION_INIT(eTableDoesNotExist, -942);
Begin
   EXECUTE IMMEDIATE ('DROP TABLE myschema.mytable');
Exception
   When eTableDoesNotExist Then
      DBMS_Output.Put_Line('Table already does not exist.');
End;

What is console.log?

It will post a log message to the browser's javascript console, e.g. Firebug or Developer Tools (Chrome / Safari) and will show the line and file where it was executed from.

Moreover, when you output a jQuery Object it will include a reference to that element in the DOM, and clicking it will go to that in the Elements/HTML tab.

You can use various methods, but beware that for it to work in Firefox, you must have Firebug open, otherwise the whole page will crash. Whether what you're logging is a variable, array, object or DOM element, it will give you a full breakdown including the prototype for the object as well (always interesting to have a poke around). You can also include as many arguments as you want, and they will be replaced by spaces.

console.log(  myvar, "Logged!");
console.info( myvar, "Logged!");
console.warn( myvar, "Logged!");
console.debug(myvar, "Logged!");
console.error(myvar, "Logged!");

These show up with different logos for each command.

You can also use console.profile(profileName); to start profiling a function, script etc. And then end it with console.profileEnd(profileName); and it will show up in you Profiles tab in Chrome (don't know with FF).

For a complete reference go to http://getfirebug.com/logging and I suggest you read it. (Traces, groups, profiling, object inspection).

Hope this helps!

how to activate a textbox if I select an other option in drop down box

Coded an example at http://jsbin.com/orisuv

HTML

<select name="color" onchange='checkvalue(this.value)'> 
    <option>pick a color</option>  
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
</select> 
<input type="text" name="color" id="color" style='display:none'/>

Javascript

function checkvalue(val)
{
    if(val==="others")
       document.getElementById('color').style.display='block';
    else
       document.getElementById('color').style.display='none'; 
}

How to add image to canvas

here is the sample code to draw image on canvas-

$("#selectedImage").change(function(e) {

var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;

img.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");        

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, 500, 500);
}});

In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:

http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html

How to list all functions in a Python module?

For completeness' sake, I'd like to point out that sometimes you may want to parse code instead of importing it. An import will execute top-level expressions, and that could be a problem.

For example, I'm letting users select entry point functions for packages being made with zipapp. Using import and inspect risks running astray code, leading to crashes, help messages being printed out, GUI dialogs popping up and so on.

Instead I use the ast module to list all the top-level functions:

import ast
import sys

def top_level_functions(body):
    return (f for f in body if isinstance(f, ast.FunctionDef))

def parse_ast(filename):
    with open(filename, "rt") as file:
        return ast.parse(file.read(), filename=filename)

if __name__ == "__main__":
    for filename in sys.argv[1:]:
        print(filename)
        tree = parse_ast(filename)
        for func in top_level_functions(tree.body):
            print("  %s" % func.name)

Putting this code in list.py and using itself as input, I get:

$ python list.py list.py
list.py
  top_level_functions
  parse_ast

Of course, navigating an AST can be tricky sometimes, even for a relatively simple language like Python, because the AST is quite low-level. But if you have a simple and clear use case, it's both doable and safe.

Though, a downside is that you can't detect functions that are generated at runtime, like foo = lambda x,y: x*y.

How do I find which application is using up my port?

To see which ports are available on your machine run:

C:>  netstat -an |find /i "listening"

Apache POI Excel - how to configure columns to be expanded?

For Excel POI:

sheetName.autoSizeColumn(cellnum); 

How to "pretty" format JSON output in Ruby on Rails

I have used the gem CodeRay and it works pretty well. The format includes colors and it recognises a lot of different formats.

I have used it on a gem that can be used for debugging rails APIs and it works pretty well.

By the way, the gem is named 'api_explorer' (http://www.github.com/toptierlabs/api_explorer)

How do I Validate the File Type of a File Upload?

From javascript, you should be able to get the filename in the onsubmit handler. So in your case, you should do something like:

<form onsubmit="if (document.getElementById('fileUpload').value.match(/xls$/) || document.getElementById('fileUpload').value.match(/xlsx$/)) { alert ('Bad file type') ; return false; } else { return true; }">...</form>

How to hide html source & disable right click and text copy?

You cannot effectively hide your HTML and JavaScript code, even if you encrypt or minify it.

If the code you're trying to hide is really sensitive, it should either be in a protected area of the site, i.e. an area that you can only access via a username and password, or potentially in a client application that isn't exposed via the web.

If you have to expose the application functionality via a web frontend, you could use Silverlight to write the frontend or bits of the frontend. In the old days you could also use ActiveX.

Foreach with JSONArray and JSONObject

Apparently, org.json.simple.JSONArray implements a raw Iterator. This means that each element is considered to be an Object. You can try to cast:

for(Object o: arr){
    if ( o instanceof JSONObject ) {
        parse((JSONObject)o);
    }
}

This is how things were done back in Java 1.4 and earlier.

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

Include files from parent or other directory

Depends on where the file you are trying to include from is located.

Example:

/rootdir/pages/file.php

/someotherDir/index.php

If you wrote the following in index.php: include('/rootdir/pages/file.php');it would error becuase it would try to get:

/someotherDir/rootdir/pages/file.php Which of course doesn't exist...

So you would have to use include('../rootdir/pages/file.php');

SystemError: Parent module '' not loaded, cannot perform relative import

if you just run the main.py under the app, just import like

from mymodule import myclass

if you want to call main.py on other folder, use:

from .mymodule import myclass

for example:

+-- app
¦   +-- __init__.py
¦   +-- main.py
¦   +-- mymodule.py
+-- __init__.py
+-- run.py

main.py

from .mymodule import myclass

run.py

from app import main
print(main.myclass)

So I think the main question of you is how to call app.main.

If condition inside of map() React

This one I found simple solutions:

row = myArray.map((cell, i) => {

    if (i == myArray.length - 1) {
      return <div> Test Data 1</div>;
    }
    return <div> Test Data 2</div>;
  });

memcpy() vs memmove()

The difference between memcpy and memmove is that

  1. in memmove, the source memory of specified size is copied into buffer and then moved to destination. So if the memory is overlapping, there are no side effects.

  2. in case of memcpy(), there is no extra buffer taken for source memory. The copying is done directly on the memory so that when there is memory overlap, we get unexpected results.

These can be observed by the following code:

//include string.h, stdio.h, stdlib.h
int main(){
  char a[]="hare rama hare rama";

  char b[]="hare rama hare rama";

  memmove(a+5,a,20);
  puts(a);

  memcpy(b+5,b,20);
  puts(b);
}

Output is:

hare hare rama hare rama
hare hare hare hare hare hare rama hare rama

Datatable to html Table

If your'e using Web Forms then Grid View can work very nicely for this

The code looks a little like this.

aspx page.

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name,Size,Quantity,Amount,Duration"></asp:GridView>

You can either input the data manually or use the source method in the code side

public class Room
{
    public string Name
    public double Size {get; set;}
    public int Quantity {get; set;}
    public double Amount {get; set;}
    public int Duration {get; set;}
}

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)//this is so you can keep any data you want for the list
    {
        List<Room> rooms=new List<Room>();
        //then use the rooms.Add() to add the rooms you need.
        GridView1.DataSource=rooms
        GridView1.Databind()
    }
}

Personally I like MVC4 the client side code ends up much lighter than Web Forms. It is similar to the above example with using a class but you use a view and Controller instead.

The View would look like this.

@model YourProject.Model.IEnumerable<Room>

<table>
    <th>
        <td>@Html.LabelFor(model => model.Name)</td>
        <td>@Html.LabelFor(model => model.Size)</td>
        <td>@Html.LabelFor(model => model.Quantity)</td>
        <td>@Html.LabelFor(model => model.Amount)</td>
        <td>@Html.LabelFor(model => model.Duration)</td>
   </th>
foreach(item in model)
{
    <tr>
        <td>@model.Name</td>
        <td>@model.Size</td>
        <td>@model.Quantity</td>
        <td>@model.Amount</td>
        <td>@model.Duration</td>
   </tr>
}
</table>

The controller might look something like this.

public ActionResult Index()
{
    List<Room> rooms=new List<Room>();
    //again add the items you need

    return View(rooms);
}

Hope this helps :)

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

If you do have a legitimate need to run some js from a partial, here's how you could do it, jQuery is required:

<script type="text/javascript">        
    function scriptToExecute()
    {
        //The script you want to execute when page is ready.           
    }

    function runWhenReady()
    {
        if (window.$)
            scriptToExecute();                                   
        else
            setTimeout(runWhenReady, 100);
    }
    runWhenReady();
</script>

Android Layout Right Align

This is an example for a RelativeLayout:

RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                relativeLayout.setLayoutParams(params);

With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.

HTTP Request in Swift with POST method

All the answers here use JSON objects. This gave us problems with the $this->input->post() methods of our Codeigniter controllers. The CI_Controller cannot read JSON directly. We used this method to do it WITHOUT JSON

func postRequest() {
    // Create url object
    guard let url = URL(string: yourURL) else {return}

    // Create the session object
    let session = URLSession.shared

    // Create the URLRequest object using the url object
    var request = URLRequest(url: url)

    // Set the request method. Important Do not set any other headers, like Content-Type
    request.httpMethod = "POST" //set http method as POST

    // Set parameters here. Replace with your own.
    let postData = "param1_id=param1_value&param2_id=param2_value".data(using: .utf8)
    request.httpBody = postData

    // Create a task using the session object, to run and return completion handler
    let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
    guard error == nil else {
        print(error?.localizedDescription ?? "Response Error")
        return
    }
    guard let serverData = data else {
        print("server data error")
        return
    }
    do {
        if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
            print("Response: \(requestJson)")
        }
    } catch let responseError {
        print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
        let message = String(bytes: serverData, encoding: .ascii)
        print(message as Any)
    }

    // Run the task
    webTask.resume()
}

Now your CI_Controller will be able to get param1 and param2 using $this->input->post('param1') and $this->input->post('param2')

Check which element has been clicked with jQuery

Use this, I think I can get your idea.

Live demo: http://jsfiddle.net/oscarj24/h722g/1/

$('body').click(function(e) {

    var target = $(e.target), article;

    if (target.is('#news_gallery li .over')) {
       article = $('#news-article .news-article');
    } else if (target.is('#work_gallery li .over')) {
       article = $('#work-article .work-article');
    } else if (target.is('#search-item li')) {
       article = $('#search-item .search-article');
    }

    if (article) {
       // Do Something
    }
});?

How to call a vue.js function on page load

Beware that when the mounted event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.

To really simulate the DOM onload event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted:

mounted: function () {
  this.$nextTick(function () {
    // Will be executed when the DOM is ready
  })
}

HTML anchor link - href and onclick both?

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
  //code
  return true;
}

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

Sort matrix according to first column in R

The accepted answer works like a charm unless you're applying it to a vector. Since a vector is non-recursive, you'll get an error like this

$ operator is invalid for atomic vectors

You can use [ in that case

foo[order(foo["V1"]),]

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

How to run a script file remotely using SSH

If you want to execute a local script remotely without saving that script remotely you can do it like this:

cat local_script.sh | ssh user@remotehost 'bash -'

It works like a charm for me.

I do that even from Windows to Linux given that you have MSYS installed on your Windows computer.

Change navbar color in Twitter Bootstrap

Example

Just try it like this:

<!-- A light one -->
<nav class="navbar navbar-default" role="navigation"></nav>
<!-- A dark one -->
<nav class="navbar navbar-inverse" role="navigation"></nav>

File navabr.css

/* Navbar */
.navbar-default {
    background-color: #F8F8F8;
    border-color: #E7E7E7;
}
/* Title */
.navbar-default .navbar-brand {
    color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
    color: #5E5E5E;
}
/* Link */
.navbar-default .navbar-nav > li > a {
    color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
    color: #333;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #555;
    background-color: #E7E7E7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
    color: #555;
    background-color: #D5D5D5;
}
/* Caret */
.navbar-default .navbar-nav > .dropdown > a .caret {
    border-top-color: #777;
    border-bottom-color: #777;
}
.navbar-default .navbar-nav > .dropdown > a:hover .caret,
.navbar-default .navbar-nav > .dropdown > a:focus .caret {
    border-top-color: #333;
    border-bottom-color: #333;
}
.navbar-default .navbar-nav > .open > a .caret,
.navbar-default .navbar-nav > .open > a:hover .caret,
.navbar-default .navbar-nav > .open > a:focus .caret {
    border-top-color: #555;
    border-bottom-color: #555;
}
/* Mobile version */
.navbar-default .navbar-toggle {
    border-color: #DDD;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
    background-color: #DDD;
}
.navbar-default .navbar-toggle .icon-bar {
    background-color: #CCC;
}
@media (max-width: 767px) {
    .navbar-default .navbar-nav .open .dropdown-menu > li > a {
        color: #777;
    }
    .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
    .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
        color: #333;
    }
}

The default major color uses are as below:

  • Navbar Background: #F8F8F8
  • Navbar Border: #E7E7E7
  • Default Color: #777
  • Nav-brand Hover Color: #5E5E5E
  • Hover Color: #333
  • Active Background: #D5D5D5
  • Active Color: #555

You can learn more in To change navbar color in Twitter Bootstrap 3.

How to use onResume()?

Restarting the app will call OnCreate().

Continuing the app when it is paused will call OnResume(). From the official docs at https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle here's a diagram of the activity lifecycle.

the Android activity lifecycle, from https://developer.android.com/images/activity_lifecycle.png on https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

how to download file using AngularJS and calling MVC API?

per various post... you cannot trigger a download via XHR. I needed to implement condition for the download, so, My solution was:

//make the call to the api with the ID to validate
someResource.get( { id: someId }, function(data) {
     //confirm that the ID is validated
     if (data.isIdConfirmed) {
         //get the token from the validation and issue another call
         //to trigger the download
         window.open('someapi/print/:someId?token='+ data.token);
     }
});

I wish that somehow, or someday the download can be triggered using XHR to avoid the second call. // _e

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

Remove servlet.jar from source web-inf/lib folder as it is available in tomcat lib folder then it works fine

How should the ViewModel close the form?

I used attached behaviours to close the window. Bind a "signal" property on your ViewModel to the attached behaviour (I actually use a trigger) When it's set to true, the behaviour closes the window.

http://adammills.wordpress.com/2009/07/01/window-close-from-xaml/

Updates were rejected because the tip of your current branch is behind its remote counterpart

This just happened to me.

  • I made a pull request to our master yesterday.
  • My colleague was reviewing it today and saw that it was out of sync with our master branch, so with the intention of helping me, he merged master to my branch.
  • I didn't know he did that.
  • Then I merged master locally, tried to push it, but it failed. Why? Because my colleague merge with master created an extra commit I did not have locally!

Solution: Pull down my own branch so I get that extra commit. Then push it back to my remote branch.

literally what I did on my branch was:

git pull
git push

What is the best method to merge two PHP objects?

I would go with linking the second object into a property of the first object. If the second object is the result of a function or method, use references. Ex:

//Not the result of a method
$obj1->extra = new Class2();

//The result of a method, for instance a factory class
$obj1->extra =& Factory::getInstance('Class2');

Add Expires headers

In ASP.NET there is similar object, you can use Caching Portions in WebFormsUserControls in order to cache objects of a page for a period of time and save server resources. This is also known as fragment caching.
If you include this code to top of your user control, a version of the control stored in the output cache for 150 seconds. You can create your own control that would contain expire header for a specific resource you want.

<%@ OutputCache Duration="150" VaryByParam="None" %>

This article explain it completely: Caching Portions of an ASP.NET Page

Detect key input in Python

You could make a little Tkinter app:

import Tkinter as tk

def onKeyPress(event):
    text.insert('end', 'You pressed %s\n' % (event.char, ))

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()

How to use System.Net.HttpClient to post a complex type?

This is the code I wound up with, based upon the other answers here. This is for an HttpPost that receives and responds with complex types:

Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync(
                       strMyHttpPostURL,
                       new MyComplexObject { Param1 = param1, Param2 = param2}).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
                    //debug:
                    //String s = response.Result.Content.ReadAsStringAsync().Result;
                    MyOtherComplexType moct = (MyOtherComplexType)JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result, typeof(MyOtherComplexType));

Get button click inside UITableViewCell

Swift 2.2

You need to add target for that button.

myButton.addTarget(self, action: #selector(ClassName.FunctionName(_:), forControlEvents: .TouchUpInside)

FunctionName: connected // for example

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

func connected(sender: UIButton) {
    let buttonTag = sender.tag
    // Do any additional setup
}

How can I git stash a specific file?

EDIT: Since git 2.13, there is a command to save a specific path to the stash: git stash push <path>. For example:

git stash push -m welcome_cart app/views/cart/welcome.thtml

OLD ANSWER:

You can do that using git stash --patch (or git stash -p) -- you'll enter interactive mode where you'll be presented with each hunk that was changed. Use n to skip the files that you don't want to stash, y when you encounter the one that you want to stash, and q to quit and leave the remaining hunks unstashed. a will stash the shown hunk and the rest of the hunks in that file.

Not the most user-friendly approach, but it gets the work done if you really need it.

How to index into a dictionary?

Addressing an element of dictionary is like sitting on donkey and enjoy the ride.

As a rule of Python, a DICTIONARY is orderless

If there is

dic = {1: "a", 2: "aa", 3: "aaa"}

Now suppose if I go like dic[10] = "b", then it will not add like this always

dic = {1:"a",2:"aa",3:"aaa",10:"b"}

It may be like

dic = {1: "a", 2: "aa", 3: "aaa", 10: "b"}

Or

dic = {1: "a", 2: "aa", 10: "b", 3: "aaa"}

Or

dic = {1: "a", 10: "b", 2: "aa", 3: "aaa"}

Or any such combination.

So a rule of thumb is that a DICTIONARY is orderless!

Should I use PATCH or PUT in my REST API?

The R in REST stands for resource

(Which isn't true, because it stands for Representational, but it's a good trick to remember the importance of Resources in REST).

About PUT /groups/api/v1/groups/{group id}/status/activate: you are not updating an "activate". An "activate" is not a thing, it's a verb. Verbs are never good resources. A rule of thumb: if the action, a verb, is in the URL, it probably is not RESTful.

What are you doing instead? Either you are "adding", "removing" or "updating" an activation on a Group, or if you prefer: manipulating a "status"-resource on a Group. Personally, I'd use "activations" because they are less ambiguous than the concept "status": creating a status is ambiguous, creating an activation is not.

  • POST /groups/{group id}/activation Creates (or requests the creation of) an activation.
  • PATCH /groups/{group id}/activation Updates some details of an existing activation. Since a group has only one activation, we know what activation-resource we are referring to.
  • PUT /groups/{group id}/activation Inserts-or-replaces the old activation. Since a group has only one activation, we know what activation-resource we are referring to.
  • DELETE /groups/{group id}/activation Will cancel, or remove the activation.

This pattern is useful when the "activation" of a Group has side-effects, such as payments being made, mails being sent and so on. Only POST and PATCH may have such side-effects. When e.g. a deletion of an activation needs to, say, notify users over mail, DELETE is not the right choice; in that case you probably want to create a deactivation resource: POST /groups/{group_id}/deactivation.

It is a good idea to follow these guidelines, because this standard contract makes it very clear for your clients, and all the proxies and layers between the client and you, know when it is safe to retry, and when not. Let's say the client is somewhere with flaky wifi, and its user clicks on "deactivate", which triggers a DELETE: If that fails, the client can simply retry, until it gets a 404, 200 or anything else it can handle. But if it triggers a POST to deactivation it knows not to retry: the POST implies this.
Any client now has a contract, which, when followed, will protect against sending out 42 emails "your group has been deactivated", simply because its HTTP-library kept retrying the call to the backend.

Updating a single attribute: use PATCH

PATCH /groups/{group id}

In case you wish to update an attribute. E.g. the "status" could be an attribute on Groups that can be set. An attribute such as "status" is often a good candidate to limit to a whitelist of values. Examples use some undefined JSON-scheme:

PATCH /groups/{group id} { "attributes": { "status": "active" } }
response: 200 OK

PATCH /groups/{group id} { "attributes": { "status": "deleted" } }
response: 406 Not Acceptable

Replacing the resource, without side-effects use PUT.

PUT /groups/{group id}

In case you wish to replace an entire Group. This does not necessarily mean that the server actually creates a new group and throws the old one out, e.g. the ids might remain the same. But for the clients, this is what PUT can mean: the client should assume he gets an entirely new item, based on the server's response.

The client should, in case of a PUT request, always send the entire resource, having all the data that is needed to create a new item: usually the same data as a POST-create would require.

PUT /groups/{group id} { "attributes": { "status": "active" } }
response: 406 Not Acceptable

PUT /groups/{group id} { "attributes": { "name": .... etc. "status": "active" } }
response: 201 Created or 200 OK, depending on whether we made a new one.

A very important requirement is that PUT is idempotent: if you require side-effects when updating a Group (or changing an activation), you should use PATCH. So, when the update results in e.g. sending out a mail, don't use PUT.

Position one element relative to another in CSS

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">
  <div class="top left"></div>
  <div class="top right"></div>
  <div class="bottom left"></div>
  <div class="bottom right"></div>
</div>

And this CSS should work:

#container {
  position: relative;
}

#container > * {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

...

Object Dump JavaScript

Firebug + console.log(myObjectInstance)

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

Specify multiple attribute selectors in CSS

[class*="test"],[class="second"] {
background: #ffff00;
}

Mailx send html message

It's easy, if your mailx command supports the -a (append header) option:

$ mailx -a 'Content-Type: text/html' -s "my subject" [email protected] < email.html

If it doesn't, try using sendmail:

# create a header file
$ cat mailheader
To: [email protected]
Subject: my subject
Content-Type: text/html

# send
$ cat mailheader email.html | sendmail -t

How do files get into the External Dependencies in Visual Studio C++?

The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

It's a table-valued function, but you're using it as a scalar function.

Try:

where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)

But... also consider changing your function into an inline TVF, as it'll perform better.

How to cancel an $http request in AngularJS?

This feature was added to the 1.1.5 release via a timeout parameter:

var canceler = $q.defer();
$http.get('/someUrl', {timeout: canceler.promise}).success(successCallback);
// later...
canceler.resolve();  // Aborts the $http request if it isn't finished.

How to apply font anti-alias effects in CSS?

Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:

body { 
    -webkit-font-smoothing: antialiased;
    text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
    background: url('./images/background.png');
    text-align: left;
    margin: auto;

}

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

We ran into this problem and tracked it down to the Geocoding.net NuGet package that we were using to help with our Google Maps views (Geocoding.net version 3.1.0 published 2/4/2014).

The Geocoding dll appears to be .Net 4.0 when you examine the package file or view it using Jet Brains’ Dot Peek application; however, a colleague of mine says that it was compiled using ilmerge so it is most likely related to the ilmerge problems listed above.

It was a long process to track it down. We fetched different changesets from TFS till we narrowed it down to the changeset that added the aforementioned NuGet package. After removing it, we were able to deploy to our .NET 4 server.

How Can I Remove “public/index.php” in the URL Generated Laravel?

Option 1: Use .htaccess

If it isn't already there, create an .htaccess file in the Laravel root directory. Create a .htaccess file your Laravel root directory if it does not exists already. (Normally it is under your public_html folder)

Edit the .htaccess file so that it contains the following code:

<IfModule mod_rewrite.c>
   RewriteEngine On 
   RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

Now you should be able to access the website without the "/public/index.php/" part.

Option 2 : Move things in the '/public' directory to the root directory

Make a new folder in your root directory and move all the files and folder except public folder. You can call it anything you want. I'll use "laravel_code".

Next, move everything out of the public directory and into the root folder. It should result in something somewhat similar to this: enter image description here

After that, all we have to do is edit the locations in the laravel_code/bootstrap/paths.php file and the index.php file.

In laravel_code/bootstrap/paths.php find the following line of code:

'app' => __DIR__.'/../app',
'public' => __DIR__.'/../public',

And change them to:

'app' => __DIR__.'/../app',
'public' => __DIR__.'/../../',

In index.php, find these lines:

require __DIR__.'/../bootstrap/autoload.php';     
$app = require_once __DIR__.'/../bootstrap/start.php';

And change them to:

require __DIR__.'/laravel_code/bootstrap/autoload.php';     
$app = require_once __DIR__.'/laravel_code/bootstrap/start.php';

Source: How to remove /public/ from URL in Laravel

What does "all" stand for in a makefile?

The manual for GNU Make gives a clear definition for all in its list of standard targets.

If the author of the Makefile is following that convention then the target all should:

  1. Compile the entire program, but not build documentation.
  2. Be the the default target. As in running just make should do the same as make all.

To achieve 1 all is typically defined as a .PHONY target that depends on the executable(s) that form the entire program:

.PHONY : all
all : executable

To achieve 2 all should either be the first target defined in the make file or be assigned as the default goal:

.DEFAULT_GOAL := all

Having a UITextField in a UITableViewCell

I ran into the same problem. It seems that setting the cell.textlabel.text property brings the UILabel to the front of the contentView of the cell. Add the textView after setting textLabel.text, or (if that's not possible) call this:

[cell.contentView bringSubviewToFront:textField]

Routing with multiple Get methods in ASP.NET Web API

Only one route enough for this

config.Routes.MapHttpRoute("DefaultApiWithAction", "{controller}/{action}");

And need to specify attribute HttpGet or HttpPost in all actions.

[HttpGet]
public IEnumerable<object> TestGet1()
{
    return new string[] { "value1", "value2" };
}

[HttpGet]
public IEnumerable<object> TestGet2()
{
    return new string[] { "value3", "value4" };
}

Converting string to byte array in C#

First of all, add the System.Text namespace

using System.Text;

Then use this code

string input = "some text"; 
byte[] array = Encoding.ASCII.GetBytes(input);

Hope to fix it!

How do you use variables in a simple PostgreSQL script?

For use variables in for example alter table:

DO $$ 
DECLARE name_pk VARCHAR(200);
BEGIN
select constraint_name
from information_schema.table_constraints
where table_schema = 'schema_name'
      and table_name = 'table_name'
      and constraint_type = 'PRIMARY KEY' INTO name_pk;
IF (name_pk := '') THEN
EXECUTE 'ALTER TABLE schema_name.table_name DROP CONSTRAINT ' || name_pk;

Angularjs ng-model doesn't work inside ng-if

You can use $parent to refer to the model defined in the parent scope like this

<input type="checkbox" ng-model="$parent.testb" />

Graphical DIFF programs for linux

Subclipse for Eclipse has an excellent graphical diff plugin if you are using SVN (subversion) source control.

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

This is the script I use. A bit tricky but it works. Tested on SQL Server 2012.

DECLARE @backupPath nvarchar(400);
DECLARE @sourceDb nvarchar(50);
DECLARE @sourceDb_log nvarchar(50);
DECLARE @destDb nvarchar(50);
DECLARE @destMdf nvarchar(100);
DECLARE @destLdf nvarchar(100);
DECLARE @sqlServerDbFolder nvarchar(100);

SET @sourceDb = 'db1'
SET @sourceDb_log = @sourceDb + '_log'
SET @backupPath = 'E:\tmp\' + sourceDb + '.bak' --ATTENTION: file must already exist and SQL Server must have access to it
SET @sqlServerDbFolder = 'E:\DB SQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\'
SET @destDb = 'db2'
SET @destMdf = @sqlServerDbFolder + @destDb + '.mdf'
SET @destLdf = @sqlServerDbFolder + @destDb + '_log' + '.ldf'

BACKUP DATABASE @sourceDb TO DISK = @backupPath

RESTORE DATABASE @destDb FROM DISK = @backupPath
WITH REPLACE,
   MOVE @sourceDb     TO @destMdf,
   MOVE @sourceDb_log TO @destLdf

javascript onclick increment number

<body>
    <input type="button" value="Increase" id="inc" onclick="incNumber()"/>
    <input type="button" value="Decrease" id="dec" onclick="decNumber()"/>

    <label id="display"></label>

    <script type="text/javascript">

    var i = 0;

    function incNumber() {
        if (i < 10) {
            i++;
        } else if (i = 10) {
            i = 0;
        }
        document.getElementById("display").innerHTML = i;
    }

    function decNumber() {
        if (i > 0) {
            --i;
        } else if (i = 0) {
            i = 10;
        }
        document.getElementById("display").innerHTML = i;
    }
    </script>
</body>

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

It's possible that the HTML5 Doctype is causing you problems with those older browsers. It could also be down to something funky related to the HTML5 shiv.

You could try switching to one of the XHTML doctypes and changing your markup accordingly, at least temporarily. This might allow you to narrow the problem down.

Is your design breaking when those IEs switch to quirks mode? If it's your CSS causing things to display strangely, it might be worth working on the CSS so the site looks the same even when the browsers switch modes.

Bootstrap 3 2-column form layout

You could use the bootstrap grid system :

<div class="col-md-6 form-group">
    <label for="textbox1">Label1</label>
    <input class="form-control" id="textbox1" type="text"/>
</div>
<div class="col-md-6 form-group">
    <label for="textbox2">Label2</label>
    <input class="form-control" id="textbox2" type="text"/>
</div>
<span class="clearfix">

http://getbootstrap.com/css/#grid

Is that what you want to achieve?

How to convert int to date in SQL Server 2008

You can't convert an integer value straight to a date but you can first it to a datetime then to a date type

select cast(40835 as datetime)

and then convert to a date (SQL 2008)

select cast(cast(40835 as datetime) as date)

cheers

Shuffle an array with python, randomize array item order with python

I don't know I used random.shuffle() but it return 'None' to me, so I wrote this, might helpful to someone

def shuffle(arr):
    for n in range(len(arr) - 1):
        rnd = random.randint(0, (len(arr) - 1))
        val1 = arr[rnd]
        val2 = arr[rnd - 1]

        arr[rnd - 1] = val1
        arr[rnd] = val2

    return arr

Batch script to install MSI

Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like

  • Using start /wait
  • Using !ERRORLEVEL! variable instead of %ERRORLEVEL%
  • Using SetLocal EnableDelayedExpansion

Nothing works and what mostly annoys me it's the fact that it works in the command line.

Best HTTP Authorization header type for JWT

Short answer

The Bearer authentication scheme is what you are looking for.

Long answer

Is it related to bears?

Errr... No :)

According to the Oxford Dictionaries, here's the definition of bearer:

bearer /'b??r?/
noun

  1. A person or thing that carries or holds something.

  2. A person who presents a cheque or other order to pay money.

The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.

And here's the definition of bearer token according to the RFC 6750:

1.2. Terminology

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer scheme for access tokens in applications that don't use OAuth 2.0.

Stick to the standards as much as you can and don't create your own authentication schemes.


An access token must be sent in the Authorization request header using the Bearer authentication scheme:

2.1. Authorization Request Header Field

When sending the access token in the Authorization request header field defined by HTTP/1.1, the client uses the Bearer authentication scheme to transmit the access token.

For example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

[...]

Clients SHOULD make authenticated requests with a bearer token using the Authorization request header field with the Bearer HTTP authorization scheme. [...]

In case of invalid or missing token, the Bearer scheme should be included in the WWW-Authenticate response header:

3. The WWW-Authenticate Response Header Field

If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP WWW-Authenticate response header field [...].

All challenges defined by this specification MUST use the auth-scheme value Bearer. This scheme MUST be followed by one or more auth-param values. [...].

For example, in response to a protected resource request without authentication:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

And in response to a protected resource request with an authentication attempt using an expired access token:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                         error="invalid_token",
                         error_description="The access token expired"

How to declare an ArrayList with values?

Use:

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

If you don't want to add new elements to the list later, you can also use (Arrays.asList returns a fixed-size list):

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

Note: you can also use a static import if you like, then it looks like this:

import static java.util.Arrays.asList;

...

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

or

List<String> x = asList("xyz", "abc");

How do you set a JavaScript onclick event to a class with css

You could do it with jQuery.

$('.myClass').click(function() {
  alert('hohoho');
});

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

In C#, why is String a reference type that behaves like a value type?

It is not a value type because performance (space and time!) would be terrible if it were a value type and its value had to be copied every time it were passed to and returned from methods, etc.

It has value semantics to keep the world sane. Can you imagine how difficult it would be to code if

string s = "hello";
string t = "hello";
bool b = (s == t);

set b to be false? Imagine how difficult coding just about any application would be.

What does <T> denote in C#

It is a generic type parameter, see Generics documentation.

T is not a reserved keyword. T, or any given name, means a type parameter. Check the following method (just as a simple example).

T GetDefault<T>()
{
    return default(T);
}

Note that the return type is T. With this method you can get the default value of any type by calling the method as:

GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00

.NET uses generics in collections, ... example:

List<int> integerList = new List<int>();

This way you will have a list that only accepts integers, because the class is instancited with the type T, in this case int, and the method that add elements is written as:

public class List<T> : ...
{
    public void Add(T item);
}

Some more information about generics.

You can limit the scope of the type T.

The following example only allows you to invoke the method with types that are classes:

void Foo<T>(T item) where T: class
{
}

The following example only allows you to invoke the method with types that are Circle or inherit from it.

void Foo<T>(T item) where T: Circle
{
}

And there is new() that says you can create an instance of T if it has a parameterless constructor. In the following example T will be treated as Circle, you get intellisense...

void Foo<T>(T item) where T: Circle, new()
{
    T newCircle = new T();
}

As T is a type parameter, you can get the object Type from it. With the Type you can use reflection...

void Foo<T>(T item) where T: class
{
    Type type = typeof(T);
}

As a more complex example, check the signature of ToDictionary or any other Linq method.

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

There isn't a T, however there is TKey and TSource. It is recommended that you always name type parameters with the prefix T as shown above.

You could name TSomethingFoo if you want to.

Error message Strict standards: Non-static method should not be called statically in php

return false is usually meant to terminate the object creation with a failure. It is as simple as that.

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

I agree with chrylis: you believe you changed your project's compliance settings but probably you didnt.

Right click on your project and:

  • Java / Build Path : Go to Libraries tab and ensure yourself that you are really using jre6
  • Java / Compiler : Ensure yourself that you have selected 1.6 compliance

By the way you can "tell" eclipse that jre8 is 1.6 compliance clicking on Window/Preferences/Java/Installed JREs/Execution Environment and selecting in the left panel, Execution Environments, JavaSE-1.6 and in the Compatible JRE's panel, jre8

CSS background-image - What is the correct usage?

just check the directory structure where exactly image is suppose you have a css folder and images folder outside css folder then you will have to use"../images/image.jpg" and it will work as it did for me just make sure the directory stucture.

Eclipse java debugging: source not found

I had this problem while working on java code to do process on a excel file containing a data set, then convert it to .csv file, i tried answers to this post, but they did not work. the problem was the jar files themselves. after downloading needed jar files one by one(older releases) and add them to my project, "source not found" error vanished. maybe you can check your jar files. hope this would help.

How to set a default entity property value with Hibernate

i'am working with hibernate 5 and postgres, and this worked form me.

@Column(name = "ACCOUNT_TYPE", ***nullable***=false, columnDefinition="varchar2 default 'END_USER'")
@Enumerated(EnumType.STRING)
private AccountType accountType;

Copy table from one database to another

Create a linked server to the source server. The easiest way is to right click "Linked Servers" in Management Studio; it's under Management -> Server Objects.

Then you can copy the table using a 4-part name, server.database.schema.table:

select  *
into    DbName.dbo.NewTable
from    LinkedServer.DbName.dbo.OldTable

This will both create the new table with the same structure as the original one and copy the data over.

How to delete all rows from all tables in a SQL Server database?

This answer builds on Zach Smith's answer by resetting the identity column as well:

  1. Disabling all constraints
  2. Iterating through all tables except those you choose to exclude
  3. Deletes all rows from the table
  4. Resets the identity column if one exists
  5. Re-enables all constraints

Here is the query:

-- Disable all constraints in the database
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

declare @catalog nvarchar(250);
declare @schema nvarchar(250);
declare @tbl nvarchar(250);
DECLARE i CURSOR LOCAL FAST_FORWARD FOR select
                                        TABLE_CATALOG,
                                        TABLE_SCHEMA,
                                        TABLE_NAME
                                        from INFORMATION_SCHEMA.TABLES
                                        where
                                        TABLE_TYPE = 'BASE TABLE'
                                        AND TABLE_NAME != 'sysdiagrams'
                                        AND TABLE_NAME != '__RefactorLog'
                                        -- Optional
                                        -- AND (TABLE_SCHEMA = 'dbo')

OPEN i;
FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @sql NVARCHAR(MAX) = N'DELETE FROM [' + @catalog + '].[' + @schema + '].[' + @tbl + '];'
        /* Make sure these are the commands you want to execute before executing */
        PRINT 'Executing statement: ' + @sql
        --EXECUTE sp_executesql @sql

        -- Reset identity counter if one exists
        IF ((SELECT OBJECTPROPERTY( OBJECT_ID(@catalog + '.' + @schema + '.' + @tbl), 'TableHasIdentity')) = 1)
        BEGIN
            SET @sql = N'DBCC CHECKIDENT ([' + @catalog + '.' + @schema + '.' + @tbl + '], RESEED, 0)'
            PRINT 'Executing statement: ' + @sql
            --EXECUTE sp_executesql @sql
        END     

        FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
    END
CLOSE i;
DEALLOCATE i;

-- Re-enable all constraints again
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

iOS: Modal ViewController with transparent background

If you are using modal segue, make sure to set it as this image (you can turn off animation if you want)enter image description here

GCD to perform task in main thread

No you don't need to check if you're in the main thread. Here is how you can do this in Swift:

runThisInMainThread { () -> Void in
    runThisInMainThread { () -> Void in
        // No problem
    }
}

func runThisInMainThread(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions

SQL using sp_HelpText to view a stored procedure on a linked server

It's the correct way to access linked DB:

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText 'storedProcName'

But make sure to mention dbo as it owns the sp_helptext.

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Old question but anyway !

Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)

So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!

How to randomize two ArrayLists in the same fashion?

The simplest approach is to encapsulate the two values together into a type which has both the image and the file. Then build an ArrayList of that and shuffle it.

That improves encapsulation as well, giving you the property that you'll always have the same number of files as images automatically.

An alternative if you really don't like that idea would be to write the shuffle code yourself (there are plenty of examples of a modified Fisher-Yates shuffle in Java, including several on Stack Overflow I suspect) and just operate on both lists at the same time. But I'd strongly recommend going with the "improve encapsulation" approach.

Sending HTML mail using a shell script

Using CentOS 7's default mailx (appears as heirloom-mailx), I've simplified this to just using a text file with your required headers and a static boundary for multipart/mixed and multipart/alternative setup.

I'm sure you can figure out multipart/related if you want with the same setup.

test.txt:

--000000000000f3b2150570186a0e
Content-Type: multipart/alternative; boundary="000000000000f3b2130570186a0c"

--000000000000f3b2130570186a0c
Content-Type: text/plain; charset="UTF-8"

This is my plain text stuff here, in case the email client does not support HTML or is blocking it purposely

My Link Here <http://www.example.com>

--000000000000f3b2130570186a0c
Content-Type: text/html; charset="UTF-8"

<div dir="ltr">
<div>This is my HTML version of the email</div>
<div><br></div>
<div><a href="http://www.example.com">My Link Here</a><br></div>
</div>

--000000000000f3b2130570186a0c--
--000000000000f3b2150570186a0e
Content-Type: text/csv; charset="US-ASCII"; name="test.csv"
Content-Disposition: attachment; filename="test.csv"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_jj5qmzqz0

The boundaries define multipart segments.

The boundary ID that has no dashes at the end is a start point of a segment.

The one with the two dashes at the end is the end point.

In this example, there's a subpart within the multipart/mixed main section, for multipart/alternative.

The multipart/alternative method basically says "Fallback to this, IF the priority part does not succeed" - in this example HTML is taken as priority normally by email clients. If an email client won't display the HTML, it falls back to the plain text.

The multipart/mixed method which encapsulates this whole message, is basically saying there's different content here, display both.

In this example, I placed a CSV file attachment on the email. You'll see the attachment get plugged in using base64 in the command below.

I threw in the attachment as an example, you'll have to set your content type appropriately for your attachment and specify whether inline or not.

The X-Attachment-Id is necessary for some providers, randomize the ID you set.

The command to mail this is:

echo -e "`cat test.txt; openssl base64 -e < test.csv`\n--000000000000f3b2150570186a0e--\n" | mailx -s "Test 2 $( echo -e "\nContent-Type: multipart/mixed; boundary=\"000000000000f3b2150570186a0e\"" )" -r [email protected] [email protected]

As you can see in the mailx Subject line I insert the multipart boundary statically, this is the first header the email client will see.

Then comes the test.txt contents being dumped.

Regarding the attachment, I use openssl (which is pretty standard on systems) to convert the file attachment to base64.

Additionally, I added the boundary close statement at the end of this echo, to signify the end of the message.

This works around heirloom-mailx problems and is virtually script-less.

The echo can be a feed instead, or any other number of methods.

Opening the Settings app from another app

In Swift 3 / iOS 10+ this now looks like

if let url = URL(string: "App-Prefs:root=LOCATION_SERVICES") {
    UIApplication.shared.open(url, completionHandler: .none)
}

Entity Framework vs LINQ to SQL

If your database is straightforward and simple, LINQ to SQL will do. If you need logical/abstracted entities on top of your tables, then go for Entity Framework.

Git merge error "commit is not possible because you have unmerged files"

This error occurs when you resolve the conflicts but the file still needs to be added in the stage area. git add . would solve it. Then, try to commit and merge.

Track a new remote branch created on GitHub

git fetch
git branch --track branch-name origin/branch-name

First command makes sure you have remote branch in local repository. Second command creates local branch which tracks remote branch. It assumes that your remote name is origin and branch name is branch-name.

--track option is enabled by default for remote branches and you can omit it.

How to do an INNER JOIN on multiple columns

something like....

SELECT f.*
      ,a1.city as from
      ,a2.city as to
FROM flights f
INNER JOIN airports a1
ON f.fairport = a1. code
INNER JOIN airports a2
ON f.tairport = a2. code

How to check if a file is empty in Bash?

[[ -s file ]] --> Checks if file has size greater than 0

if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi

If needed, this checks all the *.txt files in the current directory; and reports all the empty file:

for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done

How to set Navigation Drawer to be opened from right to left

In your main layout set your ListView gravity to right:

android:layout_gravity="right" 

Also in your code :

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item != null && item.getItemId() == android.R.id.home) {
            if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                mDrawerLayout.closeDrawer(Gravity.RIGHT);
            } 
            else {
                mDrawerLayout.openDrawer(Gravity.RIGHT);
            }
        }
        return false;
    }
};

hope it works :)

Send data from a textbox into Flask?

This worked for me.

def parse_data():
    if request.method == "POST":
        data = request.get_json()
        print(data['answers'])
        return render_template('output.html', data=data)
$.ajax({
      type: 'POST',
      url: "/parse_data",
      data: JSON.stringify({values}),
      contentType: "application/json;charset=utf-8",
      dataType: "json",
      success: function(data){
        // do something with the received data
      }
    });

What is a regex to match ONLY an empty string?

I would use a negative lookahead for any character:

^(?![\s\S])

This can only match if the input is totally empty, because the character class will match any character, including any of the various newline characters.

Url decode UTF-8 in Python

You can achieve an expected result with requests library as well:

import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")

Output:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip

Might be handy if you are already using requests, without using another library for this job.

Using logging in multiple modules

You could also come up with something like this!

def get_logger(name=None):
    default = "__app__"
    formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')
    log_map = {"__app__": "app.log", "__basic_log__": "file1.log", "__advance_log__": "file2.log"}
    if name:
        logger = logging.getLogger(name)
    else:
        logger = logging.getLogger(default)
    fh = logging.FileHandler(log_map[name])
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.setLevel(logging.DEBUG)
    return logger

Now you could use multiple loggers in same module and across whole project if the above is defined in a separate module and imported in other modules were logging is required.

a=get_logger("__app___")
b=get_logger("__basic_log__")
a.info("Starting logging!")
b.debug("Debug Mode")

Initialize Array of Objects using NSArray

No one commenting on the randomAge method?

This is so awfully wrong, it couldn't be any wronger.

NSInteger is a primitive type - it is most likely typedef'd as int or long. In the randomAge method, you calculate a number from about 1 to 98.

Then you can cast that number to an NSNumber. You had to add a cast because the compiler gave you a warning that you didn't understand. That made the warning go away, but left you with an awful bug: That number was forced to be a pointer, so now you have a pointer to an integer somewhere in the first 100 bytes of memory.

If you access an NSInteger through the pointer, your program will crash. If you write through the pointer, your program will crash. If you put it into an array or dictionary, your program will crash.

Change it either to NSInteger or int, which is probably the best, or to NSNumber if you need an object for some reason. Then create the object by calling [NSNumber numberWithInteger:99] or whatever number you want.

How to create a HTML Table from a PHP array?

Array into table. Array into div. JSON into table. JSON into div.

All are nicely handle this class. Click here to get a class

How to use it?

Just get and object

$obj = new Arrayinto();

Create an array you want to convert

$obj->array_object = array("AAA" => "1111",
                  "BBB" => "2222",
                  "CCC" => array("CCC-1" => "123",
                                 "CCC-2" => array("CCC-2222-A" => "CA2",
                                                  "CCC-2222=B" => "CB2"
                                                 )
                                )

                 );

If you want to convert Array into table. Call this.

$result = $obj->process_table();

If you want to convert Array into div. Call this.

$result = $obj->process_div();

Let suppose if you have a JSON

$obj->json_string = '{
            "AAA":"11111",
            "BBB":"22222",
            "CCC":[
                    {
                        "CCC-1":"123"
                    },
                    {
                        "CCC-2":"456"
                    }
                  ] 
         }
        ';

You can convert into table/div like this

$result = $obj->process_json('div');

OR

$result = $obj->process_json('table');

Receive JSON POST with PHP

Try;

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];

From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.

EDIT

Maybe also worth trying to echo the json string from php://input.

echo file_get_contents('php://input');

How can I start PostgreSQL on Windows?

Remove Postmaster file in "C:\Program Files\PostgreSQL\9.6\data"

and restart the PostgreSQL services

Convert datetime object to a String of date only in Python

If you want the time as well, just go with

datetime.datetime.now().__str__()

Prints 2019-07-11 19:36:31.118766 in console for me

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

For more info on this click here.

Example

<div id="header_id" class="header_class">Text</div>

#header_id {font-color:#fff}
.header_class {font-color:#000}

(Note that CSS uses the prefix # for IDs and . for Classes.)

However color was an HTML 4.01 <font> tag attribute deprecated in HTML 5. In CSS there is no "font-color", the style is color so the above should read:

Example

<div id="header_id" class="header_class">Text</div>

#header_id {color:#fff}
.header_class {color:#000}

The text would be white.

How to Compare a long value is equal to Long value

I will share that How do I do it since Java 7 -

Long first = 12345L, second = 123L;
System.out.println(first.equals(second));

output returned : false

and second example of match is -

Long first = 12345L, second = 12345L;
System.out.println(first.equals(second));

output returned : true

So, I believe in equals method for comparing Object's value, Hope it helps you, thanks.

How to make a HTML Page in A4 paper size page(s)?

Ages ago, in November 2005, AlistApart.com published an article on how they published a book using nothing but HTML and CSS. See: http://alistapart.com/article/boom

Here's an excerpt of that article:

CSS2 has a notion of paged media (think sheets of paper), as opposed to continuous media (think scrollbars). Style sheets can set the size of pages and their margins. Page templates can be given names and elements can state which named page they want to be printed on. Also, elements in the source document can force page breaks. Here is a snippet from the style sheet we used:

@page {
   size: 7in 9.25in;
   margin: 27mm 16mm 27mm 16mm;
}

Having a US-based publisher, we were given the page size in inches. We, being Europeans, continued with metric measurements. CSS accepts both.

After setting the up the page size and margin, we needed to make sure there are page breaks in the right places. The following excerpt shows how page breaks are generated after chapters and appendices:

div.chapter, div.appendix {
    page-break-after: always;
}

Also, we used CSS2 to declare named pages:

div.titlepage {
  page: blank;
}

That is, the title page is to be printed on pages with the name “blank.” CSS2 described the concept of named pages, but their value only becomes apparent when headers and footers are available.

Anyway…

Since you want to print A4, you'll need different dimensions of course:

@page {
    size: 21cm 29.7cm;
    margin: 30mm 45mm 30mm 45mm;
     /* change the margins as you want them to be. */
}

The article dives into things like setting page-breaks, etc. so you might want to read that completely.

In your case, the trick is to create the print CSS first. Most modern browsers (>2005) support zooming and will already be able to display a website based on the print CSS.

Now, you'll want to make the web display look a bit different and adapt the whole design to fit most browsers too (including the old, pre 2005 ones). For that, you'll have to create a web CSS file or override some parts of your print CSS. When creating CSS for web display, remember that a browser can have ANY size (think: “mobile” up to “big-screen TVs”). Meaning: for the web CSS your page-width and image-width is best set using a variable width (%) to support as many display devices and web-browsing clients as possible.

EDIT (26-02-2015)

Today, I happened to stumble upon another, more recent article at SmashingMagazine which also dives into designing for print with HTML and CSS… just in case you could use yet-another-tutorial.

EDIT (30-10-2018)

It has been brought to my attention in that size is not valid CSS3, which is indeed correct — I merely repeated the code quoted in the article which (as noted) was good old CSS2 (which makes sense when you look at the year the article and this answer were first published). Anyway, here's the valid CSS3 code for your copy-and-paste convenience:

@media print {
    body{
        width: 21cm;
        height: 29.7cm;
        margin: 30mm 45mm 30mm 45mm; 
        /* change the margins as you want them to be. */
   } 
}

In case you think you really need pixels (you should actually avoid using pixels), you will have to take care of choosing the correct DPI for printing:

  • 72 dpi (web) = 595 X 842 pixels
  • 300 dpi (print) = 2480 X 3508 pixels
  • 600 dpi (high quality print) = 4960 X 7016 pixels

Yet, I would avoid the hassle and simply use cm (centimeters) or mm (millimeters) for sizing as that avoids rendering glitches that can arise depending on which client you use.

Handling file renames in git

Git will recognise the file from the contents, rather than seeing it as a new untracked file

That's where you went wrong.

It's only after you add the file, that git will recognize it from content.

How to completely remove a dialog on close

An ugly solution that works like a charm for me:

$("#mydialog").dialog(
    open: function(){
        $('div.ui-widget-overlay').hide();
        $("div.ui-dialog").not(':first').remove();
}
});

Safe navigation operator (?.) or (!.) and null property paths

Since TypeScript 3.7 was released you can use optional chaining now.

Property example:

let x = foo?.bar.baz();

This is equvalent to:

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();

Moreover you can call:

Optional Call

function(otherFn: (par: string) => void) {
   otherFn?.("some value");
}

otherFn will be called only if otherFn won't be equal to null or undefined

Usage optional chaining in IF statement

This:

if (someObj && someObj.someProperty) {
    // ...
}

can be replaced now with this

if (someObj?.someProperty) {
    // ...
}

Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

How can I perform a reverse string search in Excel without using VBA?

=RIGHT(A1,LEN(A1)-FIND("`*`",SUBSTITUTE(A1," ","`*`",LEN(A1)-LEN(SUBSTITUTE(A1," ",""))))) 

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

this is probably about you don't entered correct dependency version. you can select correct dependency from this:

file>menu>project structure>app>dependencies>+>Library Dependency>select any thing you need > OK

if cannot find your needs you should update your sdk from below way:

tools>android>sdk manager>sdk update>select any thing you need>ok

Xcode build failure "Undefined symbols for architecture x86_64"

It looks like you are missing including the IOBluetooth.framework in your project. You can add it by:

  • Clicking on your project in the upper left of the left pane (the blue icon).

  • In the middle pane, click on the Build Phases tab.

  • Under "Link Binary With Libraries", click on the plus button.

  • Find the IOBluetooth.framework from the list and hit Add.

enter image description here

enter image description here

This will make sure that the IOBluetooth.framework definitions are found by the linker. You can see that the framework is a member of your target by clicking on the framework in the left pane and seeing the framework's target membership in the right pane (note I've moved the framework under the Frameworks group for organization purposes):

enter image description here

How to set value of input text using jQuery

Here is another variation for a file upload that has a nicer looking bootstrap button than the default file upload browse button. This is the html:

<div class="form-group">
        @Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "col-md-2  control-label" })
        <div class="col-md-1 btn btn-sn btn-primary" id="browseButton" onclick="$(this).parent().find('input[type=file]').click();">browse</div>
        <div class="col-md-7">
            <input id="fileSpace" name="uploaded_file"  type="file" style="display: none;">   @*style="display: none;"*@
            @Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control", @id = "modelField"} })
            @Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
        </div>
    </div>

Here is the script:

        $('#fileSpace').on("change", function () {
        $("#modelField").val($('input[name="uploaded_file"]').val());

PowerShell : retrieve JSON object by field value

In regards to PowerShell 5.1 (this is so much easier in PowerShell 7)...

Operating off the assumption that we have a file named jsonConfigFile.json with the following content from your post:

{
    "Stuffs": [
        {
            "Name": "Darts",
            "Type": "Fun Stuff"
        },
        {
            "Name": "Clean Toilet",
            "Type": "Boring Stuff"
        }
    ]
}

This will create an ordered hashtable from a JSON file to help make retrieval easier:

$json = [ordered]@{}

(Get-Content "jsonConfigFile.json" -Raw | ConvertFrom-Json).PSObject.Properties |
    ForEach-Object { $json[$_.Name] = $_.Value }

$json.Stuffs will list a nice hashtable, but it gets a little more complicated from here. Say you want the Type key's value associated with the Clean Toilet key, you would retrieve it like this:

$json.Stuffs.Where({$_.Name -eq "Clean Toilet"}).Type

It's a pain in the ass, but if your goal is to use JSON on a barebones Windows 10 installation, this is the best way to do it as far as I've found.

How to read the content of a file to a string in C?

If "read its contents into a string" means that the file does not contain characters with code 0, you can also use getdelim() function, that either accepts a block of memory and reallocates it if necessary, or just allocates the entire buffer for you, and reads the file into it until it encounters a specified delimiter or end of file. Just pass '\0' as the delimiter to read the entire file.

This function is available in the GNU C Library, http://www.gnu.org/software/libc/manual/html_mono/libc.html#index-getdelim-994

The sample code might look as simple as

char* buffer = NULL;
size_t len;
ssize_t bytes_read = getdelim( &buffer, &len, '\0', fp);
if ( bytes_read != -1) {
  /* Success, now the entire file is in the buffer */

How to send email attachments?

Other answers are excellent, though I still wanted to share a different approach in case someone is looking for alternatives.

Main difference here is that using this approach you can use HTML/CSS to format your message, so you can get creative and give some styling to your email. Though you aren't enforced to use HTML, you can also still use only plain text.

Notice that this function accepts sending the email to multiple recipients and also allows to attach multiple files.

I've only tried this on Python 2, but I think it should work fine on 3 as well:

import os.path
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication

def send_email(subject, message, from_email, to_email=[], attachment=[]):
    """
    :param subject: email subject
    :param message: Body content of the email (string), can be HTML/CSS or plain text
    :param from_email: Email address from where the email is sent
    :param to_email: List of email recipients, example: ["[email protected]", "[email protected]"]
    :param attachment: List of attachments, exmaple: ["file1.txt", "file2.txt"]
    """
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ", ".join(to_email)
    msg.attach(MIMEText(message, 'html'))

    for f in attachment:
        with open(f, 'rb') as a_file:
            basename = os.path.basename(f)
            part = MIMEApplication(a_file.read(), Name=basename)

        part['Content-Disposition'] = 'attachment; filename="%s"' % basename
        msg.attach(part)

    email = smtplib.SMTP('your-smtp-host-name.com')
    email.sendmail(from_email, to_email, msg.as_string())

I hope this helps! :-)

How to initialize a static array?

If you are creating an array then there is no difference, however, the following is neater:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

But, if you want to pass an array into a method you have to call it like this:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

prevent property from being serialized in web API

Instead of letting everything get serialized by default, you can take the "opt-in" approach. In this scenario, only the properties you specify are allowed to be serialized. You do this with the DataContractAttribute and DataMemberAttribute, found in the System.Runtime.Serialization namespace.

The DataContactAttribute is applied to the class, and the DataMemberAttribute is applied to each member you want to be serialized:

[DataContract]
public class MyClass {

  [DataMember]
  public int Id { get; set;} // Serialized

  [DataMember]
  public string Name { get; set; } // Serialized

  public string DontExposeMe { get; set; } // Will not be serialized
}

Dare I say this is a better approach because it forces you to make explicit decisions about what will or will not make it through serialization. It also allows your model classes to live in a project by themselves, without taking a dependency on JSON.net just because somewhere else you happen to be serializing them with JSON.net.

How to use fetch in typescript

Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.

That being said, the following works...

 fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then((res: Actor) => {
          // res is now an Actor
      });

I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...

callBack: (response: any) => void

But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...

fetch(`http://swapi.co/api/people/1/`)
  .then(res => res.json())
  .then(res => {
      if (callback) {
        callback(res);    // Client receives the response as desired type.  
      }
  });

So that a client can call it with a callback like...

(response: IApigeeResponse) => {
    // Process response as an IApigeeResponse
}

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

Operation Not Permitted when on root - El Capitan (rootless disabled)

Correct solution is to copy or install to /usr/local/bin not /usr/bin.This is due to System Integrity Protection (SIP). SIP makes /usr/bin read-only but leaves /usr/local as read-write.

SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.

As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."

Get first day of week in SQL Server

For the basic (the current week's Sunday)

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) as date)

If previous week:

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) -7 as date)

Internally, we built a function that does it but if you need quick and dirty, this will do it.

NULL vs nullptr (Why was it replaced?)

nullptr is always a pointer type. 0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:

f(int);
f(foo *);

How to slice a Pandas Data Frame by position?

df.ix[10,:] gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive

Add Bootstrap Glyphicon to Input Box

The official method. No custom CSS required :

<form class="form-inline" role="form">
  <div class="form-group has-success has-feedback">
    <label class="control-label" for="inputSuccess4"></label>
    <input type="text" class="form-control" id="inputSuccess4">
    <span class="glyphicon glyphicon-user form-control-feedback"></span>
  </div>
</form>

DEMO : http://jsfiddle.net/yajf3b7q

This demo is based on an example in Bootstrap docs. Scroll down to "With Optional Icons" here http://getbootstrap.com/css/#forms-control-validation

enter image description here

Secure random token in Node.js

Look at real_ates ES2016 way, it's more correct.

ECMAScript 2016 (ES7) way

import crypto from 'crypto';

function spawnTokenBuf() {
    return function(callback) {
        crypto.randomBytes(48, callback);
    };
}

async function() {
    console.log((await spawnTokenBuf()).toString('base64'));
};

Generator/Yield Way

var crypto = require('crypto');
var co = require('co');

function spawnTokenBuf() {
    return function(callback) {
        crypto.randomBytes(48, callback);
    };
}

co(function* () {
    console.log((yield spawnTokenBuf()).toString('base64'));
});

Message Queue vs. Web Services?

Message queues are asynchronous and can retry a number of times if delivery fails. Use a message queue if the requester doesn't need to wait for a response.

The phrase "web services" make me think of synchronous calls to a distributed component over HTTP. Use web services if the requester needs a response back.

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

Spring default behavior for lazy-init

lazy-init is the attribute of bean. The values of lazy-init can be true and false. If lazy-init is true, then that bean will be initialized when a request is made to bean. This bean will not be initialized when the spring container is initialized and if lazy-init is false then the bean will be initialized with the spring container initialization.

Bootstrap table without stripe / borders

Since Bootstrap v4.1 you can add table-borderless to your table, see official documentation:

<table class='table table-borderless'>

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

Extract and delete all .gz in a directory- Linux

Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 tar xvfz

Then Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 rm

This will untar all .tar.gz files in the current directory and then delete all the .tar.gz files. If you want an explanation, the "|" takes the stdout of the command before it, and uses that as the stdin of the command after it. Use "man command" w/o the quotes to figure out what those commands and arguments do. Or, you can research online.

How to sort an array based on the length of each element?

This code should do the trick:

var array = ["ab", "abcdefgh", "abcd"];

array.sort(function(a, b){return b.length - a.length});

console.log(JSON.stringify(array, null, '\t'));

What is the best way to remove accents (normalize) in a Python unicode string?

Actually I work on project compatible python 2.6, 2.7 and 3.4 and I have to create IDs from free user entries.

Thanks to you, I have created this function that works wonders.

import re
import unicodedata

def strip_accents(text):
    """
    Strip accents from input String.

    :param text: The input string.
    :type text: String.

    :returns: The processed String.
    :rtype: String.
    """
    try:
        text = unicode(text, 'utf-8')
    except (TypeError, NameError): # unicode is a default on python 3 
        pass
    text = unicodedata.normalize('NFD', text)
    text = text.encode('ascii', 'ignore')
    text = text.decode("utf-8")
    return str(text)

def text_to_id(text):
    """
    Convert input text to id.

    :param text: The input string.
    :type text: String.

    :returns: The processed String.
    :rtype: String.
    """
    text = strip_accents(text.lower())
    text = re.sub('[ ]+', '_', text)
    text = re.sub('[^0-9a-zA-Z_-]', '', text)
    return text

result:

text_to_id("Montréal, über, 12.89, Mère, Françoise, noël, 889")
>>> 'montreal_uber_1289_mere_francoise_noel_889'

Change input text border color without changing its height

This css solution worked for me:

input:active,
input:focus {
    border: 1px solid #red
}

input:active,
input:focus {
    padding: 2px solid #red /*for firefox and chrome*/
}

/* .ie is a class you would need to set at the html root level */
.ie input:active,
.ie input:focus {
    padding: 3px solid #red /* IE needs 1px extra padding*/
}

I understand it is not necessary on FF and Chrome, but IE needs it. And there are circumstances when you need it.

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

    Windows PowerShell
    Copyright (C) 2014 Microsoft Corporation. All rights reserved.

    PS C:\Windows\system32> **$dte = Get-Date**
    PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
    PS C:\Windows\system32> **$PastDueDate**

    Sunday, March 1, 2020 12:00:00 AM

   PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
   PS C:\Windows\system32> **$NewDateFormat 03012020**

There're few additional methods available as well e.g.: $dte.AddDays(-45).Day

Sizing elements to percentage of screen width/height

FractionallySizedBox may also be useful. You can also read the screen width directly out of MediaQuery.of(context).size and create a sized box based on that

MediaQuery.of(context).size.width * 0.65

if you really want to size as a fraction of the screen regardless of what the layout is.

SQL to Query text in access with an apostrophe in it

When you include a string literal in a query, you can enclose the string in either single or double quotes; Access' database engine will accept either. So double quotes will avoid the problem with a string which contains a single quote.

SELECT * FROM tblStudents WHERE [name] Like "Daniel O'Neal";

If you want to keep the single quotes around your string, you can double up the single quote within it, as mentioned in other answers.

SELECT * FROM tblStudents WHERE [name] Like 'Daniel O''Neal';

Notice the square brackets surrounding name. I used the brackets to lessen the chance of confusing the database engine because name is a reserved word.

It's not clear why you're using the Like comparison in your query. Based on what you've shown, this should work instead.

SELECT * FROM tblStudents WHERE [name] = "Daniel O'Neal";

iterating through json object javascript

An improved version for recursive approach suggested by @schirrmacher to print key[value] for the entire object:

var jDepthLvl = 0;
function visit(object, objectAccessor=null) {
  jDepthLvl++;
  if (isIterable(object)) {
    if(objectAccessor === null) {
      console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- START ? ?", "background:yellow");
    } else
      console.log("%c"+spacesDepth(jDepthLvl)+objectAccessor+"%c:","color:purple;font-weight:bold", "color:black");
    forEachIn(object, function (accessor, child) {
      visit(child, accessor);
    });
  } else {
    var value = object;
    console.log("%c"
      + spacesDepth(jDepthLvl)
      + objectAccessor + "[%c" + value + "%c] "
      ,"color:blue","color:red","color:blue");
  }
  if(objectAccessor === null) {
    console.log("%c ? ? printing object $OBJECT_OR_ARRAY$ -- END ? ?", "background:yellow");
  }
  jDepthLvl--;
}

function spacesDepth(jDepthLvl) {
  let jSpc="";
  for (let jIter=0; jIter<jDepthLvl-1; jIter++) {
    jSpc+="\u0020\u0020"
  }
  return jSpc;
}

function forEachIn(iterable, functionRef) {
  for (var accessor in iterable) {
    functionRef(accessor, iterable[accessor]);
  }
}

function isIterable(element) {
  return isArray(element) || isObject(element);
}

function isArray(element) {
  return element.constructor == Array;
}

function isObject(element) {
  return element.constructor == Object;
}


visit($OBJECT_OR_ARRAY$);

Console Output using JSON from @eric

How to set Angular 4 background image?

this one is working for me also for internet explorer:

<div class="col imagebox" [ngStyle]="bkUrl"></div>

...

@Input() background = '571x450img';  
bkUrl = {};   
ngOnInit() {
    this.bkUrl = this.getBkUrl();
  }
getBkUrl() {
    const styles = {
      'background-image': 'url(src/assets/images/' + this.background + '.jpg)'
    };
    console.log(styles);
    return styles;
  }

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Just a MacOS extra update for hjpotter92 answer.

To make sed recognize the pattern in MacOS, you'll have to add a backslash before the = sign, like this:

sed -i old 's/\DEFINER\=`[^`]*`@`[^`]*`//g' file.sql

Difference between AutoPostBack=True and AutoPostBack=False?

If you want a control to postback automatically when an event is raised, you need to set the AutoPostBack property of the control to True.