Programs & Examples On #Getline

A C function that reads an entire line from a stream. It was originally a GNU extension that was standardized in POSIX.1-2008.

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

Going through a text file line by line in C

So many problems in so few lines. I probably forget some:

  • argv[0] is the program name, not the first argument;
  • if you want to read in a variable, you have to allocate its memory
  • one never loops on feof, one loops on an IO function until it fails, feof then serves to determinate the reason of failure,
  • sscanf is there to parse a line, if you want to parse a file, use fscanf,
  • "%s" will stop at the first space as a format for the ?scanf family
  • to read a line, the standard function is fgets,
  • returning 1 from main means failure

So

#include <stdio.h>

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line); 
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}

c++ Read from .csv file

Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.

This is what your code sees

0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M

Try this

0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M


while(file.good())
{

    getline(file, ID, ',');
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero) ; \\ diff
    cout << "Sexo: " <<  genero;\\diff


}

Using getline() in C++

If you're using getline() after cin >> something, you need to flush the newline character out of the buffer in between. You can do it by using cin.ignore().

It would be something like this:

string messageVar;
cout << "Type your message: ";
cin.ignore(); 
getline(cin, messageVar);

This happens because the >> operator leaves a newline \n character in the input buffer. This may become a problem when you do unformatted input, like getline(), which reads input until a newline character is found. This happening, it will stop reading immediately, because of that \n that was left hanging there in your previous operation.

Using getline() with file input in C++

ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

When and why do I need to use cin.ignore() in C++?

You're thinking about this the wrong way. You're thinking in logical steps each time cin or getline is used. Ex. First ask for a number, then ask for a name. That is the wrong way to think about cin. So you run into a race condition because you assume the stream is clear each time you ask for a input.

If you write your program purely for input you'll find the problem:

void main(void)
{
    double num;
    string mystr;

    cin >> num;
    getline(cin, mystr);

    cout << "num=" << num << ",mystr=\'" << mystr << "\'" << endl;
}

In the above, you are thinking, "first get a number." So you type in 123 press enter, and your output will be num=123,mystr=''. Why is that? It's because in the stream you have 123\n and the 123 is parsed into the num variable while \n is still in the stream. Reading the doc for getline function by default it will look in the istream until a \n is encountered. In this example, since \n is in the stream, it looks like it "skipped" it but it worked properly.

For the above to work, you'll have to enter 123Hello World which will properly output num=123,mystr='Hello World'. That, or you put a cin.ignore between the cin and getline so that it'll break into logical steps that you expect.

This is why you need the ignore command. Because you are thinking of it in logical steps rather than in a stream form so you run into a race condition.

Take another code example that is commonly found in schools:

void main(void)
{
    int age;
    string firstName;
    string lastName;

    cout << "First name: ";
    cin >> firstName;

    cout << "Last name: ";
    cin >> lastName;

    cout << "Age: ";
    cin >> age;

    cout << "Hello " << firstName << " " << lastName << "! You are " << age << " years old!" << endl;
}

The above seems to be in logical steps. First ask for first name, last name, then age. So if you did John enter, then Doe enter, then 19 enter, the application works each logic step. If you think of it in "streams" you can simply enter John Doe 19 on the "First name:" question and it would work as well and appear to skip the remaining questions. For the above to work in logical steps, you would need to ignore the remaining stream for each logical break in questions.

Just remember to think of your program input as it is reading from a "stream" and not in logical steps. Each time you call cin it is being read from a stream. This creates a rather buggy application if the user enters the wrong input. For example, if you entered a character where a cin >> double is expected, the application will produce a seemingly bizarre output.

cin and getline skipping input

I faced this issue, and resolved this issue using getchar() to catch the ('\n') new char

How to highlight text using javascript

Here's my regexp pure JavaScript solution:

function highlight(text) {
    document.body.innerHTML = document.body.innerHTML.replace(
        new RegExp(text + '(?!([^<]+)?<)', 'gi'),
        '<b style="background-color:#ff0;font-size:100%">$&</b>'
    );
}

Another git process seems to be running in this repository

Try deleting index.lock file in your .git directory.

rm -f .git/index.lock

Such problems generally occur when you execute two git commands simultaneously; maybe one from the command prompt and one from an IDE.

count number of rows in a data frame in R based on group

library(plyr)
ddply(data, .(MONTH-YEAR), nrow)

This will give you the answer, if "MONTH-YEAR" is a variable. First, try unique(data$MONTH-YEAR) and see if it returns unique values (no duplicates).

Then above simple split-apply-combine will return what you are looking for.

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Great answers, but you could just open the command prompt and type in

 SET PATH=C:\Program Files\Nodejs;%PATH%

C# get string from textbox

if in string:

string yourVar = yourTextBoxname.Text;

if in numbers:

int yourVar = int.Parse(yourTextBoxname.Text);

How to install bcmath module?

I found that the repo that had the package was not enabled. On OEL7,

$ vi /etc/yum.repos.d/ULN-Base.repo
Set enabled to 1 for ol7_optional_latest

$ yum install php-bcmath

and that worked...

I used the following command to find where the package was

$ yum --noplugins --showduplicates --enablerepo \* --disablerepo \*-source --disablerepo C5.\*,c5-media,\*debug\*,\*-source list \*bcmath

Swift - iOS - Dates and times in different format

let usDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US"))
            //usDateFormat now contains an optional string "MM/dd/yyyy"

let gbDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB"))
            //gbDateFormat now contains an optional string "dd/MM/yyyy"

let geDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "de-DE"))
            //geDateFormat now contains an optional string "dd.MM.yyyy"

You can use it in following way to get the current format from device:

let currentDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale.current)

How do I remove diacritics (accents) from a string in .NET?

I really like the concise and functional code provided by azrafe7. So, I have changed it a little bit to convert it to an extension method:

public static class StringExtensions
{
    public static string RemoveDiacritics(this string text)
    {
        const string SINGLEBYTE_LATIN_ASCII_ENCODING = "ISO-8859-8";

        if (string.IsNullOrEmpty(text))
        {
            return string.Empty;
        }

        return Encoding.ASCII.GetString(
            Encoding.GetEncoding(SINGLEBYTE_LATIN_ASCII_ENCODING).GetBytes(text));
    }
}

What is the correct way to write HTML using Javascript?

document.write() will only work while the page is being originally parsed and the DOM is being created. Once the browser gets to the closing </body> tag and the DOM is ready, you can't use document.write() anymore.

I wouldn't say using document.write() is correct or incorrect, it just depends on your situation. In some cases you just need to have document.write() to accomplish the task. Look at how Google analytics gets injected into most websites.

After DOM ready, you have two ways to insert dynamic HTML (assuming we are going to insert new HTML into <div id="node-id"></div>):

  1. Using innerHTML on a node:

    var node = document.getElementById('node-id');
    node.innerHTML('<p>some dynamic html</p>');
    
  2. Using DOM methods:

    var node = document.getElementById('node-id');
    var newNode = document.createElement('p');
    newNode.appendChild(document.createTextNode('some dynamic html'));
    node.appendChild(newNode);
    

Using the DOM API methods might be the purist way to do stuff, but innerHTML has been proven to be much faster and is used under the hood in JavaScript libraries such as jQuery.

Note: The <script> will have to be inside your <body> tag for this to work.

AngularJS ui-router login authentication

The easiest solution is to use $stateChangeStart and event.preventDefault() to cancel the state change when the user is not authenticated and redirect him to the auth state that is the login page.

angular
  .module('myApp', [
    'ui.router',
  ])
    .run(['$rootScope', 'User', '$state',
    function ($rootScope, User, $state) {
      $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if (toState.name !== 'auth' && !User.authenticaded()) {
          event.preventDefault();
          $state.go('auth');
        }
      });
    }]
  );

Convert list to array in Java

This is works. Kind of.

public static Object[] toArray(List<?> a) {
    Object[] arr = new Object[a.size()];
    for (int i = 0; i < a.size(); i++)
        arr[i] = a.get(i);
    return arr;
}

Then the main method.

public static void main(String[] args) {
    List<String> list = new ArrayList<String>() {{
        add("hello");
        add("world");
    }};
    Object[] arr = toArray(list);
    System.out.println(arr[0]);
}

What is the easiest way to encrypt a password when I save it to the registry?

If you want to be able to decrypt the password, I think the easiest way would be to use DPAPI (user store mode) to encrypt/decrypt. This way you don't have to fiddle with encryption keys, store them somewhere or hard-code them in your code - in both cases somebody can discover them by looking into registry, user settings or using Reflector.

Otherwise use hashes SHA1 or MD5 like others have said here.

how to check if string value is in the Enum list?

You can use the Enum.TryParse method:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

Why plt.imshow() doesn't display the image?

plt.imshow just finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add plt.show.

Enter key press behaves like a Tab in Javascript

You can use my code below, tested in Mozilla, IE, and Chrome

   // Use to act like tab using enter key
    $.fn.enterkeytab=function(){
         $(this).on('keydown', 'input, select,', function(e) {
        var self = $(this)
          , form = self.parents('form:eq(0)')
          , focusable
          , next
          ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select,button').filter(':visible');
                next = focusable.eq(focusable.index(this)+1);
                if (next.length) {
                    next.focus();
                } else {
                    alert("wd");
                    //form.submit();
                }
                return false;
            }
        });

    }

How to Use?

$("#form").enterkeytab(); // enter key tab

Fit image to table cell [Pure HTML]

if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:

<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

see the fiddle : http://jsfiddle.net/Lk2Rh/27/

but still it better to handling this with CSS, i suggest you that.

  • I hope this help.

javac : command not found

Make sure you install JDK/JRE first.

follow these steps:

open terminal go to your root dictionary by typing

cd /

you will see Library folder

Now follow this path Library/Java/JVM/bin

Once you get into bin you can see the javac file

Now you need to get the path of this folder for that just write this command

pwd

get the path for your javac.

Delete last commit in bitbucket

As others have said, usually you want to use hg backout or git revert. However, sometimes you really want to get rid of a commit.

First, you'll want to go to your repository's settings. Click on the Strip commits link.

Strip commits link in bitbucket settings

Enter the changeset ID for the changeset you want to destroy, and click Preview strip. That will let you see what kind of damage you're about to do before you do it. Then just click Confirm and your commit is no longer history. Make sure you tell all your collaborators what you've done, so they don't accidentally push the offending commit back.

Remove Item from ArrayList

 public void DeleteUserIMP(UserIMP useriamp) {
       synchronized (ListUserIMP) {
            if (ListUserIMP.isEmpty()) {
            System.out.println("user is empty");
        }  else {
            Iterator<UserIMP> it = ListUserIMP.iterator();
            while (it.hasNext()) {
                UserIMP user = it.next();
                if (useriamp.getMoblieNumber().equals(user.getMoblieNumber())) {
                    it.remove();
                    System.out.println("remove it");
                }
            }
            // ListUserIMP.remove(useriamp);

            System.out.println(" this user removed");
        }
        Constants.RESULT_FOR_REGISTRATION = Constants.MESSAGE_OK;
        // System.out.println("This user Deleted " + Constants.MESSAGE_OK);

    }
}

Maximum call stack size exceeded error

Nearly every answer here states that this can only be caused by an infinite loop. That's not true, you could otherwise over-run the stack through deeply nested calls (not to say that's efficient, but it's certainly in the realm of possible). If you have control of your JavaScript VM, you can adjust the stack size. For example:

node --stack-size=2000

See also: How can I increase the maximum call stack size in Node.js

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

Sockets: Discover port availability using Java

In my case I had to use DatagramSocket class.

boolean isPortOccupied(int port) {
    DatagramSocket sock = null;
    try {
        sock = new DatagramSocket(port);
        sock.close();
        return false;
    } catch (BindException ignored) {
        return true;
    } catch (SocketException ex) {
        System.out.println(ex);
        return true;
    }
}

Don't forget to import first

import java.net.DatagramSocket;
import java.net.BindException;
import java.net.SocketException;

How to escape the equals sign in properties files

In Spring or Spring boot application.properties file here is the way to escape the special characters;

table.whereclause=where id'\='100

Android Layout Weight

One more reason I found (vague as it may sound). The below did not work.

LinearLayout vertical

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

EndLinearLayout

What did work was

RelativeLayout

LinearLayout vertical

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

EndLinearLayout

EndRelativeLayout

It sounds vague by a root layout with Linear and weights under it did not work. And when I say "did not work", I mean, that after I viewed the graphical layout between various resolutions the screen consistency broke big time.

Select All Rows Using Entity Framework

Here is a few ways to do it (Just assume I'm using Dependency Injection for the DbConext)

public class Example
{
    private readonly DbContext Context;

    public Example(DbContext context)
    {
        Context = context;
    }

    public DbSetSampleOne[] DbSamples { get; set; }

    public void ExampleMethod DoSomething()
    {
        // Example 1: This will select everything from the entity you want to select
        DbSamples = Context.DbSetSampleOne.ToArray();

        // Example 2: If you want to apply some filtering use the following example
        DbSamples = Context.DbSetSampleOne.ToArray().Where(p => p.Field.Equals("some filter"))

    }

What is the C# equivalent of NaN or IsNumeric?

I was using Chris Lively's snippet (selected answer) encapsulated in a bool function like Gishu's suggestion for a year or two. I used it to make sure certain query strings were only numeric before proceeding with further processing. I started getting some errant querystrings that the marked answer was not handling, specifically, whenever a comma was passed after a number like "3645," (returned true). This is the resulting mod:

   static public bool IsNumeric(string s)
   {
      double myNum = 0;
      if (Double.TryParse(s, out myNum))
      {
         if (s.Contains(",")) return false;
         return true;
      }
      else
      {
         return false;
      }
   }

Side-by-side list items as icons within a div (css)

add this line in your css file:

.classname ul li {
    float: left;
}

Getting the difference between two sets

Try this

test2.removeAll(test1);

Set#removeAll

Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.

enable/disable zoom in Android WebView

Improved Lukas Knuth's version:

public class TweakedWebView extends WebView {

    private ZoomButtonsController zoomButtons;

    public TweakedWebView(Context context) {
        super(context);
        init();
    }

    public TweakedWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TweakedWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        getSettings().setBuiltInZoomControls(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getSettings().setDisplayZoomControls(false);
        } else {
            try {
                Method method = getClass()
                        .getMethod("getZoomButtonsController");
                zoomButtons = (ZoomButtonsController) method.invoke(this);
            } catch (Exception e) {
                // pass
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean result = super.onTouchEvent(ev);
        if (zoomButtons != null) {
            zoomButtons.setVisible(false);
            zoomButtons.getZoomControls().setVisibility(View.GONE);
        }
        return result;
    }

}

How to check if two arrays are equal with JavaScript?

var a= [1, 2, 3, '3'];
var b = [1, 2, 3];

var c = a.filter(function (i) { return ! ~b.indexOf(i); });

alert(c.length);

Why do I get PLS-00302: component must be declared when it exists?

I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.

401 Unauthorized: Access is denied due to invalid credentials

I realize this is an older post but I had the same error on IIS 8.5. Hopefully this can help another experiencing the same issue (I didn't see my issue outlined in other questions with a similar title).

Everything seemed set up correctly with the Application Pool Identity, but I continued to receive the error. After much digging, there is a setting for the anonymous user to use the credentials of the application pool identity or a specific user. For whatever reason, mine was defaulted to a specific user. Altering the setting to the App Pool Identity fixed the issue for me.

  1. IIS Manager ? Sites ? Website
  2. Double click "Authentication"
  3. Select Anonymous Authentication
  4. From the Actions panel, select Edit
  5. Select Application pool Identity and click ok

Hopefully this saves someone else some time!

jQuery delete all table rows except first

I think this is more readable given the intent:

$('someTableSelector').children( 'tr:not(:first)' ).remove();

Using children also takes care of the case where the first row contains a table by limiting the depth of the search.

If you had an TBODY element, you can do this:

$("someTableSelector > tbody:last").children().remove();

If you have THEAD or TFOOT elements you'll need to do something different.

How to add a default "Select" option to this ASP.NET DropDownList control?

If you want to make the first item unselectable, try this:

DropDownList1.Items.Insert(0, new ListItem("Select", "-1"));
DropDownList1.Items[0].Attributes.Add("disabled", "disabled");

string decode utf-8

A string needs no encoding. It is simply a sequence of Unicode characters.

You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.

Encoding of a String is carried out by:

String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into

You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).

Decoding:

String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded 

If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"

What is the difference between Sublime text and Github's Atom

I just got my beta invitation today and tried Atom right away. The GUI feels like Sublime, and yes, there some shortcuts adopted from Sublime.

Besides everything mentioned above, here are some differences I have noticed so far:

  1. Vim mode is not as good as the Vintage mode on Sublime (which is not a fully featured vim either) because the vim package is in an early stage of development. See https://atom.io/packages/vim-mode for detail.

  2. As James mention, Atom is written using web tools, so you have access to the stylesheet of the text editor (styles.less) to do whatever appearance changes you want using CSS. There is also an option to change the startup CoffeeScript.

  3. Again, because Atom is still in the beta stage, Sublime has much more native plugin packages. However, since Atom is written in Node.js, the Atom official site said you can "choose from over 50 thousand in Node's package repository." (Because I am not a Node.js pro, I haven't look into this feature though)

  4. Atom has better Github support out of the box, but Sublime has a several Git packages.

  5. Sublime is a paid application unlimited evaluation period. Atom is free at the beta stage but we don't know whether Github wants to charge it or not.

So the bottom line is Atom is a text editor built with web technology at beta stage. By contrast, Sublime has evolved through many different iterations. Atom is still missing a lot of packages that Sublime supports, so the question is will Atom catch up with Sublime or become some better? Github seems to be confident about the future of this text edit because of its popular underlying technologies, and Atom is probably going to be a good alternative to Sublime in the long run.

How can I create a unique constraint on my column (SQL Server 2008 R2)?

To create these constraints through the GUI you need the "indexes and keys" dialogue not the check constraints one.

But in your case you just need to run the piece of code you already have. It doesn't need to be entered into the expression dialogue at all.

In Java, remove empty elements from a list of Strings

Regarding the comment of Andrew Mairose - Although a fine solution, I would just like to add that this solution will not work on fixed size lists.

You could attempt doing like so:

Arrays.asList(new String[]{"a", "b", null, "c", "    "})
    .removeIf(item -> item == null || "".equals(item));

But you'll encounter an UnsupportedOperationException at java.util.AbstractList.remove(since asList returns a non-resizable List).

A different solution might be this:

List<String> collect =
    Stream.of(new String[]{"a", "b", "c", null, ""})
        .filter(item -> item != null && !"".equals(item))
        .collect(Collectors.toList());

Which will produce a nice list of strings :-)

How do you access the element HTML from within an Angular attribute directive?

I suggest using Render, as the ElementRef API doc suggests:

... take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported. Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker or Universal.

Always use the Renderer for it will make you code (or library you right) be able to work when using Universal or WebWorkers.

import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';

export class HighlightDirective {
    constructor(el: ElementRef, renderer: Renderer) {
        renderer.setElementProperty(el.nativeElement, 'innerHTML', 'some new value');
    }
}

It doesn't look like Render has a getElementProperty() method though, so I guess we still need to use NativeElement for that part. Or (better) pass the content in as an input property to the directive.

How to publish a website made by Node.js to Github Pages?

It's very simple steps to push your node js application from local to GitHub.

Steps:

  1. First create a new repository on GitHub
  2. Open Git CMD installed to your system (Install GitHub Desktop)
  3. Clone the repository to your system with the command: git clone repo-url
  4. Now copy all your application files to this cloned library if it's not there
  5. Get everything ready to commit: git add -A
  6. Commit the tracked changes and prepares them to be pushed to a remote repository: git commit -a -m "First Commit"
  7. Push the changes in your local repository to GitHub: git push origin master

How to redirect to logon page when session State time out is completed in asp.net mvc

One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.

But this is very hectic method To over come this you need to create your own ActionFilterAttribute which will do this, you just need to add this attribute in every action method.

Here is the Class which overrides ActionFilterAttribute.

public class SessionExpireFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;

            // check if session is supported
            CurrentCustomer objCurrentCustomer = new CurrentCustomer();
            objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
            if (objCurrentCustomer == null)
            {
                // check if a new session id was generated
                filterContext.Result = new RedirectResult("~/Users/Login");
                return;
            }

            base.OnActionExecuting(filterContext);
        }
    }

Then in action just add this attribute like so:

[SessionExpire]
public ActionResult Index()
{
     return Index();
}

This will do you work.

Show and hide divs at a specific time interval using jQuery

See InnerFade.

<script type="text/javascript">
    $(document).ready(

    function() {
        $('#portfolio').innerfade({
            speed: 'slow',
            timeout: 10000,
            type: 'sequence',
            containerheight: '220px'
        });
    });
</script>
<ul id="portfolio">
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/kreation/good_guy__bad_guy.html">
        <img src="images/ggbg.gif" alt="Good Guy bad Guy" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/kreation/whizzkids.html">
        <img src="images/whizzkids.gif" alt="Whizzkids" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/printdesign/koenigin_mutter.html">
        <img src="images/km.jpg" alt="Königin Mutter" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/webdesign/rt_reprotechnik_-_hybride_archivierung.html">
        <img src="images/rt_arch.jpg" alt="RT Hybride Archivierung" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/kommunikation/tuev_sued_gruppe.html">
        <img src="images/tuev.jpg" alt="TÜV SÜD Gruppe" />
        </a>
    </li>
</ul>

How to change position of Toast in Android?

Toast toast = Toast.makeText(this, "Custom toast creation", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT,0,0);
    toast.show();

How to set all elements of an array to zero or any same value?

If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.

// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};

// file scope
int arr[4];
// equivalent to
int arr[4] = {0};

Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.

// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

In my case it was a view (highly nested, view in view) insertion causing the error in :

CREATE TABLE tablename AS
  SELECT * FROM highly_nested_viewname
;

The workaround we ended up doing was simulating a materialized view (which is really a table) and periodically insert/update it using stored procedures.

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

Regular expression search replace in Sublime Text 2

Here is a visual presentation of the approved answer.

enter image description here

Writing Python lists to columns in csv

import csv
dic = {firstcol,secondcol} #dictionary
csv = open('result.csv', "w") 
for key in dic.keys():
    row ="\n"+ str(key) + "," + str(dic[key]) 
    csv.write(row)

Recursively add the entire folder to a repository

I also had the same issue and I do not have .gitignore file. My problem was solved with the following way. This took all sub-directories and files.

git add <directory>/*

Most efficient way to get table row count

$next_id = mysql_fetch_assoc(mysql_query("SELECT MAX(id) FROM table"));
$next_id['MAX(id)']; // next auto incr id

hope it helpful :)

@RequestBody and @ResponseBody annotations in Spring

Below is an example of a method in a Java controller.

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public HttpStatus something(@RequestBody MyModel myModel) 
{
    return HttpStatus.OK;
}

By using @RequestBody annotation you will get your values mapped with the model you created in your system for handling any specific call. While by using @ResponseBody you can send anything back to the place from where the request was generated. Both things will be mapped easily without writing any custom parser etc.

Remove elements from collection while iterating

I would choose the second as you don't have to do a copy of the memory and the Iterator works faster. So you save memory and time.

Dynamic SELECT TOP @var In SQL Server

In x0n's example, it should be:

SET ROWCOUNT @top

SELECT * from sometable

SET ROWCOUNT 0

http://msdn.microsoft.com/en-us/library/ms188774.aspx

Why does Git treat this text file as a binary file?

This is also caused (on Windows at least) by text files that have UTF-8 with BOM encoding. Changing the encoding to regular UTF-8 immediately made Git see the file as type=text

Printing the value of a variable in SQL Developer

1 ) Go to view menu.
2 ) Select the DBMS_OUTPUT menu item.
3 ) Press Ctrl + N and select connection editor.
4 ) Execute the SET SERVEROUTPUT ON Command.
5 ) Then execute your PL/SQL Script.

enter image description here enter image description here

Tesseract OCR simple example

Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing

Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.

Setup

To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.

Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.

VC++ Directories>Include Directories:

..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath) C/C++>Preprocessor>Preprocessor Definitions:

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) C/C++>Linker>Input>Additional Dependencies:

..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies) Now you can include headers in your project's file:

include

include

Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.

When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.

tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... Sample

You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.

redirect to current page in ASP.Net

Why Server.Transfer? Response.Redirect(Request.RawUrl) would get you what you need.

tar: Error is not recoverable: exiting now

If you got "Error is not recoverable: exiting now" You might have specified incorrect path references.

[me@host ~]$ tar -xvf nameOfMyTar.tar -C /someSubDirectory/
tar: /someSubDirectory: Cannot open: No such file or directory
tar: Error is not recoverable: exiting now
[me@host ~]$

Make sure you provide correct relative or absolute directory references e.g.:

[me@host ~]$ tar -xvf ./nameOfMyTar.tar -C ./someSubDirectory/
./foo/
./bar/
[me@host ~]$ 

Clearing Magento Log Data

Login to your c-panel goto phpmyadmin using SQL run below query to clear logs

TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;

Best way to require all files from a directory in ruby?

Dir[File.join(__dir__, "/app/**/*.rb")].each do |file|
  require file
end

This will work recursively on your local machine and a remote (Like Heroku) which does not use relative paths.

Controlling execution order of unit tests in Visual Studio

Merge your tests into one giant test will work. To make the test method more readable, you can do something like

[TestMethod]
public void MyIntegratonTestLikeUnitTest()
{
    AssertScenarioA();

    AssertScenarioB();

    ....
}

private void AssertScenarioA()
{
     // Assert
}

private void AssertScenarioB()
{
     // Assert
}

Actually the issue you have suggests you probably should improve the testability of the implementation.

How do I change the language of moment.js?

I am not sure what changed but importing the language file like this worked for me

import 'moment/src/locale/fr';
moment.locale('fr)

Notice the src in the import statement

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

Javascript: Setting location.href versus location

Like as has been said already, location is an object. But that person suggested using either. But, you will do better to use the .href version.

Objects have default properties which, if nothing else is specified, they are assumed. In the case of the location object, it has a property called .href. And by not specifying ANY property during the assignment, it will assume "href" by default.

This is all well and fine until a later object model version changes and there either is no longer a default property, or the default property is changed. Then your program breaks unexpectedly.

If you mean href, you should specify href.

Angular 2 @ViewChild annotation returns undefined

I had a similar issue and thought I'd post in case someone else made the same mistake. First, one thing to consider is AfterViewInit; you need to wait for the view to be initialized before you can access your @ViewChild. However, my @ViewChild was still returning null. The problem was my *ngIf. The *ngIf directive was killing my controls component so I couldn't reference it.

import {Component, ViewChild, OnInit, AfterViewInit} from 'angular2/core';
import {ControlsComponent} from './controls/controls.component';
import {SlideshowComponent} from './slideshow/slideshow.component';

@Component({
    selector: 'app',
    template:  `
        <controls *ngIf="controlsOn"></controls>
        <slideshow (mousemove)="onMouseMove()"></slideshow>
    `,
    directives: [SlideshowComponent, ControlsComponent]
})

export class AppComponent {
    @ViewChild(ControlsComponent) controls:ControlsComponent;

    controlsOn:boolean = false;

    ngOnInit() {
        console.log('on init', this.controls);
        // this returns undefined
    }

    ngAfterViewInit() {
        console.log('on after view init', this.controls);
        // this returns null
    }

    onMouseMove(event) {
         this.controls.show();
         // throws an error because controls is null
    }
}

Hope that helps.

EDIT
As mentioned by @Ashg below, a solution is to use @ViewChildren instead of @ViewChild.

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

It would seem like your user doesn't have permission to write to that directory on the server. Please make sure that the permissions are correct. The user will need write permissions on that directory.

What exactly does Perl's "bless" do?

This function tells the entity referenced by REF that it is now an object in the CLASSNAME package, or the current package if CLASSNAME is omitted. Use of the two-argument form of bless is recommended.

Example:

bless REF, CLASSNAME
bless REF

Return Value

This function returns the reference to an object blessed into CLASSNAME.

Example:

Following is the example code showing its basic usage, the object reference is created by blessing a reference to the package's class -

#!/usr/bin/perl

package Person;
sub new
{
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # Print all the values just for clarification.
    print "First Name is $self->{_firstName}\n";
    print "Last Name is $self->{_lastName}\n";
    print "SSN is $self->{_ssn}\n";
    bless $self, $class;
    return $self;
}

removing table border

Most of the time your background color is different from the background of your table. Since there are spaces between the cells, those spaces will create the illusion of lines with the color of the background behind the table.

The solution is to get rid of those spaces.

Inside the table tag write:

cellspacing="0"

Looping over a list in Python

You may as well use for x in values rather than for x in values[:]; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...

The code only prints one item per value of x - and x is iterating over the elements of values, which are the sublists. So it will only print each sublist once.

How can I make git accept a self signed certificate?

Using 64bit version of Git on Windows, just add the self signed CA certificate into these files :

  • C:\Program Files\Git\mingw64\ssl\certs\ca-bundle.crt
  • C:\Program Files\Git\mingw64\ssl\certs\ca-bundle.trust.crt

If it is just a server self signed certificate add it into

  • C:\Program Files\Git\mingw64\ssl\cert.pem

Vue - Deep watching an array of objects and calculating the change?

This is what I use to deep watch an object. My requirement was watching the child fields of the object.

new Vue({
    el: "#myElement",
    data:{
        entity: {
            properties: []
        }
    },
    watch:{
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected.    
            },
            deep: true
        }
    }
});

gnuplot : plotting data from multiple input files in a single graph

You're so close!

Change

plot "print_1012720" using 1:2 title "Flow 1", \
plot "print_1058167" using 1:2 title "Flow 2", \
plot "print_193548"  using 1:2 title "Flow 3", \ 
plot "print_401125"  using 1:2 title "Flow 4", \
plot "print_401275"  using 1:2 title "Flow 5", \
plot "print_401276"  using 1:2 title "Flow 6"

to

plot "print_1012720" using 1:2 title "Flow 1", \
     "print_1058167" using 1:2 title "Flow 2", \
     "print_193548"  using 1:2 title "Flow 3", \ 
     "print_401125"  using 1:2 title "Flow 4", \
     "print_401275"  using 1:2 title "Flow 5", \
     "print_401276"  using 1:2 title "Flow 6"

The error arises because gnuplot is trying to interpret the word "plot" as the filename to plot, but you haven't assigned any strings to a variable named "plot" (which is good – that would be super confusing).

How to convert Double to int directly?

int average_in_int = ( (Double) Math.ceil( sum/count ) ).intValue();

Switch case with conditions

A switch works by comparing what is in switch() to every case.

switch (cnt) {
    case 1: ....
    case 2: ....
    case 3: ....
}

works like:

if (cnt == 1) ...
if (cnt == 2) ...
if (cnt == 3) ...

Therefore, you can't have any logic in the case statements.

switch (cnt) {
    case (cnt >= 10 && cnt <= 20): ...
}

works like

if (cnt == (cnt >= 10 && cnt <= 20)) ...

and that's just nonsense. :)

Use if () { } else if () { } else { } instead.

How is __eq__ handled in Python and in what order?

When Python2.x sees a == b, it tries the following.

  • If type(b) is a new-style class, and type(b) is a subclass of type(a), and type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If type(a) has overridden __eq__ (that is, type(a).__eq__ isn't object.__eq__), then the result is a.__eq__(b).
  • If type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If none of the above are the case, Python repeats the process looking for __cmp__. If it exists, the objects are equal iff it returns zero.
  • As a final fallback, Python calls object.__eq__(a, b), which is True iff a and b are the same object.

If any of the special methods return NotImplemented, Python acts as though the method didn't exist.

Note that last step carefully: if neither a nor b overloads ==, then a == b is the same as a is b.


From https://eev.ee/blog/2012/03/24/python-faq-equality/

Disabling of EditText in Android

Use this to disable user input

android:focusable="false"

android:editable="false" This method is deprecated one.

JUnit Eclipse Plugin?

You might want to try out Quick JUnit: https://marketplace.eclipse.org/content/quick-junit

The plugin is stable and it allows switching between production and test code. I am currently using Eclipse Mars 4.5 and the plugin is supported for this release as well as for the following:

Luna (4.4), Kepler (4.3), Juno (4.2, 3.8), Previous to Juno (<=4.1)

PHP Pass by reference in foreach

Because on the second loop, $v is still a reference to the last array item, so it's overwritten each time.

You can see it like that:

$a = array ('zero','one','two', 'three');

foreach ($a as &$v) {

}

foreach ($a as $v) {
  echo $v.'-'.$a[3].PHP_EOL;
}

As you can see, the last array item takes the current loop value: 'zero', 'one', 'two', and then it's just 'two'... : )

Is 'bool' a basic datatype in C++?

C++ does lots of automatic casting for you - that is, if you have a variable of type bool and pass it to something expecting an int, it will make it into an int for you - 0 for false and 1 for true.

I don't have my standard around to see if this is guaranteed, but every compiler I've used does this (so one can assume it will always work).

However, relying on this conversion is a bad idea. Code can stop compiling if a new method is added that overloads the int signature, etc.

Find nearest latitude/longitude with an SQL query

Find nearest Users to my:

Distance in meters

Based in Vincenty's formula

i have User table:

+----+-----------------------+---------+--------------+---------------+
| id | email                 | name    | location_lat | location_long |
+----+-----------------------+---------+--------------+---------------+
| 13 | [email protected] | Isaac   | 17.2675625   | -97.6802361   |
| 14 | [email protected]   | Monse   | 19.392702    | -99.172596    |
+----+-----------------------+---------+--------------+---------------+

sql:

-- my location:  lat   19.391124   -99.165660
SELECT 
(ATAN(
    SQRT(
        POW(COS(RADIANS(users.location_lat)) * SIN(RADIANS(users.location_long) - RADIANS(-99.165660)), 2) +
        POW(COS(RADIANS(19.391124)) * SIN(RADIANS(users.location_lat)) - 
       SIN(RADIANS(19.391124)) * cos(RADIANS(users.location_lat)) * cos(RADIANS(users.location_long) - RADIANS(-99.165660)), 2)
    )
    ,
    SIN(RADIANS(19.391124)) * 
    SIN(RADIANS(users.location_lat)) + 
    COS(RADIANS(19.391124)) * 
    COS(RADIANS(users.location_lat)) * 
    COS(RADIANS(users.location_long) - RADIANS(-99.165660))
 ) * 6371000) as distance,
users.id
FROM users
ORDER BY distance ASC

radius of the earth : 6371000 ( in meters)

Extracting time from POSIXct

There have been previous answers that showed the trick. In essence:

  • you must retain POSIXct types to take advantage of all the existing plotting functions

  • if you want to 'overlay' several days worth on a single plot, highlighting the intra-daily variation, the best trick is too ...

  • impose the same day (and month and even year if need be, which is not the case here)

which you can do by overriding the day-of-month and month components when in POSIXlt representation, or just by offsetting the 'delta' relative to 0:00:00 between the different days.

So with times and val as helpfully provided by you:

## impose month and day based on first obs
ntimes <- as.POSIXlt(times)    # convert to 'POSIX list type'
ntimes$mday <- ntimes[1]$mday  # and $mon if it differs too
ntimes <- as.POSIXct(ntimes)   # convert back

par(mfrow=c(2,1))
plot(times,val)   # old times
plot(ntimes,val)  # new times

yields this contrasting the original and modified time scales:

enter image description here

Find a file in python

Below we use a boolean "first" argument to switch between first match and all matches (a default which is equivalent to "find . -name file"):

import  os

def find(root, file, first=False):
    for d, subD, f in os.walk(root):
        if file in f:
            print("{0} : {1}".format(file, d))
            if first == True:
                break 

extract the date part from DateTime in C#

DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date

if you want to compare dates, ignoring the time part, make an use of DateTime.Year and DateTime.DayOfYear properties.

code snippet

DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
    Console.WriteLine("d1 < d2");
else
    if (d1.DayOfYear < d2.DayOfYear)
        Console.WriteLine("d1 < d2");

Is there a way to force npm to generate package-lock.json?

By default, package-lock.json is updated whenever you run npm install. However, this can be disabled globally by setting package-lock=false in ~/.npmrc.

When the global package-lock=false setting is active, you can still force a project’s package-lock.json file to be updated by running:

npm install --package-lock

This command is the only surefire way of forcing a package-lock.json update.

No connection could be made because the target machine actively refused it (PHP / WAMP)

Till yesterday I was able to connect to phpMyAdmin, but today I started getting this error:

2002-no-connection-could-be-made-because-the-target-machine-actively-refused

None of the answers here really helped me fix the problem, what helped me is shared below:

I looked at the mysql logs.[C:\wamp\logs\mysql.log]

It said

2015-09-18 01:16:30 5920 [Note] Plugin 'FEDERATED' is disabled.
2015-09-18 01:16:30 5920 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-09-18 01:16:30 5920 [Note] InnoDB: The InnoDB memory heap is disabled
2015-09-18 01:16:30 5920 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-09-18 01:16:30 5920 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-09-18 01:16:30 5920 [Note] InnoDB: Not using CPU crc32 instructions
2015-09-18 01:16:30 5920 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-09-18 01:16:30 5920 [Note] InnoDB: Completed initialization of buffer pool
2015-09-18 01:16:30 5920 [Note] InnoDB: Highest supported file format is Barracuda.
2015-09-18 01:16:30 5920 [Note] InnoDB: The log sequence numbers 1765410 and 1765410 in ibdata files do not match the log sequence number 2058233 in the ib_logfiles!
2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
2015-09-18 01:16:30 5920 [Note] InnoDB: Starting crash recovery.
2015-09-18 01:16:30 5920 [Note] InnoDB: Reading tablespace information from the .ibd files...
2015-09-18 01:16:30 5920 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous tablespace harley/login_confirm uses space ID: 6 at filepath: .\harley\login_confirm.ibd. Cannot open tablespace testdb/testtable which uses space ID: 6 at filepath: .\testdb\testtable.ibd
InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.

I got the clue that this guy is creating a problem - InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd

and this line 2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!

hmmm, For me the testdb was just a test-db! hence I decided to delete this file inside C:\wamp\bin\mysql\mysql5.6.17\data\testdb

and restarted all services, and went to phpMyAdmin, and this time no issues, phpMyAdmin opened :)

How to select rows with no matching entry in another table?

Let we have the following 2 tables(salary and employee) enter image description here

Now i want those records from employee table which are not in salary. We can do this in 3 ways:

  1. Using inner Join
select * from employee
where id not in(select e.id from employee e inner join salary s on e.id=s.id)

enter image description here

  1. Using Left outer join
select * from employee e 
left outer join salary s on e.id=s.id  where s.id is null

enter image description here

  1. Using Full Join
select * from employee e
full outer join salary s on e.id=s.id where e.id not in(select id from salary)

enter image description here

Error renaming a column in MySQL

EDIT

You can rename fields using:

ALTER TABLE xyz CHANGE manufacurerid manufacturerid INT

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

How to show hidden divs on mouseover?

There is a really simple way to do this in a CSS only way.

Apply an opacity to 0, therefore making it invisible, but it will still react to JavaScript events and CSS selectors. In the hover selector, make it visible by changing the opacity value.

_x000D_
_x000D_
#mouse_over {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
#mouse_over:hover {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div style='border: 5px solid black; width: 120px; font-family: sans-serif'>_x000D_
<div style='height: 20px; width: 120px; background-color: cyan;' id='mouse_over'>Now you see me</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is it possible to move/rename files in Git and maintain their history?

I make moving the files and then do

git add -A

which put in the sataging area all deleted/new files. Here git realizes that the file is moved.

git commit -m "my message"
git push

I do not know why but this works for me.

Is there an easy way to reload css without reloading the page?

i now have this:

    function swapStyleSheet() {
        var old = $('#pagestyle').attr('href');
        var newCss = $('#changeCss').attr('href');
        var sheet = newCss +Math.random(0,10);
        $('#pagestyle').attr('href',sheet);
        $('#profile').attr('href',old);
        }
    $("#changeCss").on("click", function(event) { 
        swapStyleSheet();
    } );

make any element in your page with id changeCss with a href attribute with the new css url in it. and a link element with the starting css:

<link id="pagestyle" rel="stylesheet" type="text/css" href="css1.css?t=" />

<img src="click.jpg" id="changeCss" href="css2.css?t=">

How to install plugins to Sublime Text 2 editor?

You should have a Data/Packages folder in your Sublime Text 2 install directory. All you need to do is download the plugin and put the plugin folder in the Packages folder.

Or, an easier way would be to install the Package Control Plugin by wbond.

Just go here: https://sublime.wbond.net/installation

and follow the install instructions.

Once you are done you can use the Ctrl + Shift + P shortcut in Sublime, type in install and press enter, then search for emmet.

EDIT: You can now also press Ctrl + Shift + P right away and use the command 'Install Package Control' instead of following the install instructions. (Tested on Build 3126)

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

Droppping schema and recreating it with utf8mb4 character set solved my issue.

Swift - How to convert String to Double

Use this code in Swift 2.0

let strWithFloat = "78.65"
let floatFromString = Double(strWithFloat)

Get first 100 characters from string, respecting full words

If you define words as "sequences of characters delimited by space"... Use strrpos() to find the last space in the string, shorten to that position, trim the result.

How I can get and use the header file <graphics.h> in my C++ program?

<graphics.h> is not a standard header. Most commonly it refers to the header for Borland's BGI API for DOS and is antiquated at best.

However it is nicely simple; there is a Win32 implementation of the BGI interface called WinBGIm. It is implemented using Win32 GDI calls - the lowest level Windows graphics interface. As it is provided as source code, it is perhaps a simple way of understanding how GDI works.

WinBGIm however is by no means cross-platform. If all you want are simple graphics primitives, most of the higher level GUI libraries such as wxWidgets and Qt support that too. There are simpler libraries suggested in the possible duplicate answers mentioned in the comments.

Angular update object in object array

updateValue(data){    
     // retriving index from array
     let indexValue = this.items.indexOf(data);
    // changing specific element in array
     this.items[indexValue].isShow =  !this.items[indexValue].isShow;
}

How to top, left justify text in a <td> cell that spans multiple rows

 <td rowspan="2" style="text-align:left;vertical-align:top;padding:0">Save a lot</td>

That should do it.

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

Initializing entire 2D array with one value

If you want to initialize the array to -1 then you can use the following,

memset(array, -1, sizeof(array[0][0]) * row * count)

But this will work 0 and -1 only

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

For layering, Just change the version of targetFramework in web.config file only, the other things no need change.

PostgreSQL IF statement

You could also use the the basic structure for the PL/pgSQL CASE with anonymous code block procedure block:

DO $$ BEGIN
    CASE
        WHEN boolean-expression THEN
          statements;
        WHEN boolean-expression THEN
          statements;
        ...
        ELSE
          statements;
    END CASE;
END $$;

References:

  1. http://www.postgresql.org/docs/current/static/sql-do.html
  2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

How do emulators work and how are they written?

I wrote an article about emulating the Chip-8 system in JavaScript.

It's a great place to start as the system isn't very complicated, but you still learn how opcodes, the stack, registers, etc work.

I will be writing a longer guide soon for the NES.

Where does gcc look for C and C++ header files?

`gcc -print-prog-name=cc1plus` -v

This command asks gcc which C++ preprocessor it is using, and then asks that preprocessor where it looks for includes.

You will get a reliable answer for your specific setup.

Likewise, for the C preprocessor:

`gcc -print-prog-name=cpp` -v

ImportError: No module named PytQt5

If you are on ubuntu, just install pyqt5 with apt-get command:

    sudo apt-get install python3-pyqt5   # for python3

or

    sudo apt-get install python-pyqt5    # for python2

However, on Ubuntu 14.04 the python-pyqt5 package is left out [source] and need to be installed manually [source]

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

It depends. See the MySQL Performance Blog post on this subject: To SQL_CALC_FOUND_ROWS or not to SQL_CALC_FOUND_ROWS?

Just a quick summary: Peter says that it depends on your indexes and other factors. Many of the comments to the post seem to say that SQL_CALC_FOUND_ROWS is almost always slower - sometimes up to 10x slower - than running two queries.

Alternate table with new not null Column in existing table in SQL

You will either have to specify a DEFAULT, or add the column with NULLs allowed, update all the values, and then change the column to NOT NULL.

ALTER TABLE <YourTable> 
ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

Try ro use this like libs:

https://www.npmjs.com/package/promise-chain-break

    db.getData()
.then(pb((data) => {
    if (!data.someCheck()) {
        tellSomeone();

        // All other '.then' calls will be skiped
        return pb.BREAK;
    }
}))
.then(pb(() => {
}))
.then(pb(() => {
}))
.catch((error) => {
    console.error(error);
});

How to match any non white space character except a particular one?

You can use a character class:

/[^\s\\]/

matches anything that is not a whitespace character nor a \. Here's another example:

[abc] means "match a, b or c"; [^abc] means "match any character except a, b or c".

Convert hexadecimal string (hex) to a binary string

Integer.parseInt(hex,16);    
System.out.print(Integer.toBinaryString(hex));

Parse hex(String) to integer with base 16 then convert it to Binary String using toBinaryString(int) method

example

int num = (Integer.parseInt("A2B", 16));
System.out.print(Integer.toBinaryString(num));

Will Print

101000101011

Max Hex vakue Handled by int is FFFFFFF

i.e. if FFFFFFF0 is passed ti will give error

Cannot find control with name: formControlName in angular reactive form

I tried to generate a form dynamically because the amount of questions depend on an object and for me the error was fixed when I added ngDefaultControl to my mat-form-field.

    <form [formGroup]="questionsForm">
        <ng-container *ngFor="let question of questions">
            <mat-form-field [formControlName]="question.id" ngDefaultControl>
                <mat-label>{{question.questionContent}}</mat-label>
                <textarea matInput rows="3" required></textarea>
            </mat-form-field>
        </ng-container>
        <button mat-raised-button (click)="sendFeedback()">Submit all questions</button>
    </form>

In sendFeedback() I get the value from my dynamic form by selecting the formgroup's value as such

  sendFeedbackAsAgent():void {
    if (this.questionsForm.valid) {
      console.log(this.questionsForm.value)
    }
  }

Renaming the current file in Vim

There's a sightly larger plugin called vim-eunuch by Tim Pope that includes a rename function as well as some other goodies (delete, find, save all, chmod, sudo edit, ...).

To rename a file in vim-eunuch:

:Move filename.ext

Compared to rename.vim:

:rename[!] filename.ext

Saves a few keystrokes :)

Why do package names often begin with "com"

It's the domain name spelt out in reverse.

For example, one of my domains is hedgee.com. So, I use com.hedgee as the base name of all my packages.

Algorithm to detect overlapping periods

There is a wonderful library with good reviews on CodeProject: http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

That library does a lot of work concerning overlap, intersecting them, etc. It's too big to copy/paste all of it, but I'll see which specific parts which can be useful to you.

Where's javax.servlet?

Have you instaled the J2EE? If you installed just de standard (J2SE) it won´t find.

JQuery window scrolling event?

Try this: http://jsbin.com/axaler/3/edit

$(function(){
  $(window).scroll(function(){
    var aTop = $('.ad').height();
    if($(this).scrollTop()>=aTop){
        alert('header just passed.');
        // instead of alert you can use to show your ad
        // something like $('#footAd').slideup();
    }
  });
});

How to set date format in HTML date input tag?

If you're using jQuery, here's a nice simple method

$("#dateField").val(new Date().toISOString().substring(0, 10));

Or there's the old traditional way:

document.getElementById("dateField").value = new Date().toISOString().substring(0, 10)

What's the name for hyphen-separated case?

As the character (-) is referred to as "hyphen" or "dash", it seems more natural to name this "dash-case", or "hyphen-case" (less frequently used).

As mentioned in Wikipedia, "kebab-case" is also used. Apparently (see answer) this is because the character would look like a skewer... It needs some imagination though.
Used in lodash lib for example.

Recently, "dash-case" was used by

How do I get logs from all pods of a Kubernetes replication controller?

You can also do this by service name.

First, try to find the service name of the respective pod which corresponds to multiple pods of the same service. kubectl get svc.

Next, run the following command to display logs from each container.

kubectl logs -f service/<service-name>

How to read and write into file using JavaScript?

For Firefox:

var file = Components.classes["@mozilla.org/file/local;1"].
       createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/home");

See https://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O

For others, check out the TiddlyWiki app to see how it does it.

How can I ping a server port with PHP?

function ping($ip){
    $output = shell_exec("ping $ip");
    var_dump($output);
}
ping('127.0.0.1');

UPDATE: If you pass an hardcoded IP (like in this example and most of the real-case scenarios), this function can be enough.

But since some users seem to be very concerned about safety, please remind to never pass user generated inputs to the shell_exec function: If the IP comes from an untrusted source, at least check it with a filter before using it.

@angular/material/index.d.ts' is not a module

Accepted Answer is correct, but it didn't fully work for me. I had to delete the package.lock file, re-run "npm install", and then close and reopen my visual studio. Hope this helps someone

Example use of "continue" statement in Python?

Usually the situation where continue is necessary/useful, is when you want to skip the remaining code in the loop and continue iteration.

I don't really believe it's necessary, since you can always use if statements to provide the same logic, but it might be useful to increase readability of code.

Moment.js - tomorrow, today and yesterday

I have similar solution, but allows to use locales:

    let date = moment(someDate);
    if (moment().diff(date, 'days') >= 1) {
        return date.fromNow(); // '2 days ago' etc.
    }
    return date.calendar().split(' ')[0]; // 'Today', 'yesterday', 'tomorrow'

How to export specific request to file using postman?

To do that you need to leverage the "Collections" feature of Postman. This link could help you: https://learning.getpostman.com/docs/postman/collections/creating_collections/

Here is the way to do it:

  • Create a collection (within tab "Collections")
  • Execute your request
  • Add the request to a collection
  • Share your collection as a file

close fxml window by code, javafx

I implemented this in the following way after receiving a NullPointerException from the accepted answer.

In my FXML:

<Button onMouseClicked="#onMouseClickedCancelBtn" text="Cancel">

In my Controller class:

@FXML public void onMouseClickedCancelBtn(InputEvent e) {
    final Node source = (Node) e.getSource();
    final Stage stage = (Stage) source.getScene().getWindow();
    stage.close();
}

How do I get the path and name of the file that is currently executing?

You can use inspect.stack()

import inspect,os
inspect.stack()[0]  => (<frame object at 0x00AC2AC0>, 'g:\\Python\\Test\\_GetCurrentProgram.py', 15, '<module>', ['print inspect.stack()[0]\n'], 0)
os.path.abspath (inspect.stack()[0][1]) => 'g:\\Python\\Test\\_GetCurrentProgram.py'

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

The issue with only having these two conditions:

  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />

is that they work only as long as the {REQUEST_FILENAME} exists physically on disk. This means that there can be scenarios where a request for an incorrectly named partial view would return the root page instead of a 404 which would cause angular to be loaded twice (and in certain scenarios it can cause a nasty infinite loop).

Thus, some safe "fallback" rules would be recommended to avoid these hard to troubleshoot issues:

  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.html$" negate="true" />
  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.js$" negate="true" />
  <add input="{REQUEST_FILENAME}" pattern="(.*?)\.css$" negate="true" />

or a condition that matches any file ending:

<conditions>
  <!-- ... -->
  <add input="{REQUEST_FILENAME}" pattern=".*\.[\d\w]+$" negate="true" />
</conditions>

Render HTML to an image

HtmlToImage.jar will be the simplest way to convert a html into an image

Converting HTML to image using java

Is there a way to get colored text in GitHubflavored Markdown?

As an alternative to rendering a raster image, you can embed a SVG:

https://gist.github.com/CyberShadow/95621a949b07db295000

Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.

MySQL Multiple Joins in one query?

You can simply add another join like this:

SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data 
    INNER JOIN dashboard_messages 
        ON dashboard_message_id = dashboard_messages.id
    INNER JOIN images
        ON dashboard_messages.image_id = images.image_id 

However be aware that, because it is an INNER JOIN, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)

SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data 
    INNER JOIN dashboard_messages 
        ON dashboard_message_id = dashboard_messages.id
    LEFT OUTER JOIN images
        ON dashboard_messages.image_id = images.image_id 

What is the most effective way to get the index of an iterator of an std::vector?

According to http://www.cplusplus.com/reference/std/iterator/distance/, since vec.begin() is a random access iterator, the distance method uses the - operator.

So the answer is, from a performance point of view, it is the same, but maybe using distance() is easier to understand if anybody would have to read and understand your code.

Remove all elements contained in another array

I build the logic without using any built-in methods, please let me know any optimization or modifications. I tested in JS editor it is working fine.

var myArray = [
            {name: 'deepak', place: 'bangalore'},
            {name: 'alok', place: 'berhampur'},
            {name: 'chirag', place: 'bangalore'},
            {name: 'chandan', place: 'mumbai'},

        ];
        var toRemove = [

            {name: 'chirag', place: 'bangalore'},
            {name: 'deepak', place: 'bangalore'},
            /*{name: 'chandan', place: 'mumbai'},*/
            /*{name: 'alok', place: 'berhampur'},*/


        ];
        var tempArr = [];
        for( var i=0 ; i < myArray.length; i++){
            for( var j=0; j<toRemove.length; j++){
                var toRemoveObj = toRemove[j];
                if(myArray[i] && (myArray[i].name === toRemove[j].name)) {
                    break;
                }else if(myArray[i] && (myArray[i].name !== toRemove[j].name)){
                        var fnd = isExists(tempArr,myArray[i]);
                        if(!fnd){
                            var idx = getIdex(toRemove,myArray[i])
                            if (idx === -1){
                                tempArr.push(myArray[i]);
                            }

                        }

                    }

                }
        }
        function isExists(source,item){
            var isFound = false;
            for( var i=0 ; i < source.length; i++){
                var obj = source[i];
                if(item && obj && obj.name === item.name){
                    isFound = true;
                    break;
                }
            }
            return isFound;
        }
        function getIdex(toRemove,item){
            var idex = -1;
            for( var i=0 ; i < toRemove.length; i++){
                var rObj =toRemove[i];
                if(rObj && item && rObj.name === item.name){
                    idex=i;
                    break;
                }
            }
            return idex;
        }

Python __call__ special method practical example

This is too late but I'm giving an example. Imagine you have a Vector class and a Point class. Both take x, y as positional args. Let's imagine you want to create a function that moves the point to be put on the vector.

4 Solutions

  • put_point_on_vec(point, vec)

  • Make it a method on the vector class. e.g my_vec.put_point(point)

  • Make it a method on the Point class. my_point.put_on_vec(vec)
  • Vector implements __call__, So you can use it like my_vec_instance(point)

This is actually part of some examples I'm working on for a guide for dunder methods explained with Maths that I'm gonna release sooner or later.

I left the logic of moving the point itself because this is not what this question is about

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

If you do not intend to interact with the inner element/s in any case, then a CSS solution might be useful for you.

Just set the inner element/s to pointer-events: none

in your case:

.clickable > a {
    pointer-events: none;
}

or to target all inner elements generally:

.clickable * {
    pointer-events: none;
}

This easy hack saved me a lot of time while developing with ReactJS

Browser support could be found here: http://caniuse.com/#feat=pointer-events

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

jQuery UI dialog positioning

Taking Jaymin's example a step further, I came up with this for positioning a jQuery ui-dialog element above the element you've just clicked (think "speech bubble"):

$('#myDialog').dialog( 'open' );
var myDialogX = $(this).position().left - $(this).outerWidth();
var myDialogY = $(this).position().top - ( $(document).scrollTop() + $('.ui-dialog').outerHeight() );
$('#myDialog').dialog( 'option', 'position', [myDialogX, myDialogY] );

Note that I "open" the ui-dialog element before calculating the relative width and height offsets. This is because jQuery can't evaluate outerWidth() or outerHeight() without the ui-dialog element physically appearing in the page.

Just be sure to set 'modal' to false in your dialog options and you should be a-OK.

PHP multiline string with PHP

The internal set of single quotes in your code is killing the string. Whenever you hit a single quote it ends the string and continues processing. You'll want something like:

$thisstring = 'this string is long \' in needs escaped single quotes or nothing will run';

Repeat a task with a time delay?

For people using Kotlin, inazaruk's answer will not work, the IDE will require the variable to be initialized, so instead of using the postDelayed inside the Runnable, we'll use it in an separate method.

  • Initialize your Runnable like this :

    private var myRunnable = Runnable {
        //Do some work
        //Magic happens here ?
        runDelayedHandler(1000)   }
    
  • Initialize your runDelayedHandler method like this :

     private fun runDelayedHandler(timeToWait : Long) {
        if (!keepRunning) {
            //Stop your handler
            handler.removeCallbacksAndMessages(null)
            //Do something here, this acts like onHandlerStop
        }
        else {
            //Keep it running
            handler.postDelayed(myRunnable, timeToWait)
        }
    }
    
  • As you can see, this approach will make you able to control the lifetime of the task, keeping track of keepRunning and changing it during the lifetime of the application will do the job for you.

Floating elements within a div, floats outside of div. Why?

Thank you LSerni you solved it for me.

To achieve this :

+-----------------------------------------+
| +-------+                     +-------+ |
| | Text1 |                     | Text1 | |
| +-------+                     +-------+ |
|+----------------------------------------+

You have to do this :

<div style="overflow:auto">
    <div style="display:inline-block;float:left"> Text1 </div>
    <div style="display:inline-block;float:right"> Text2 </div>
</div>

How to Deep clone in javascript

The below function is most efficient way to deep clone javascript objects.

function deepCopy(obj){
    if (!obj || typeof obj !== "object") return obj;

    var retObj = {};

    for (var attr in obj){
        var type = obj[attr];

        switch(true){
            case (type instanceof Date):
                var _d = new Date();
                _d.setDate(type.getDate())
                retObj[attr]= _d;
                break;

            case (type instanceof Function):
                retObj[attr]= obj[attr];
                break;

            case (type instanceof Array):
                var _a =[];
                for (var e of type){
                    //_a.push(e);
                    _a.push(deepCopy(e));
                }
                retObj[attr]= _a;
                break;

            case (type instanceof Object):
                var _o ={};
                for (var e in type){
                    //_o[e] = type[e];
                    _o[e] = deepCopy(type[e]);
                }
                retObj[attr]= _o;
                break;

            default:
                retObj[attr]= obj[attr];
        }
    }
    return retObj;
}

var obj = {
    string: 'test',
    array: ['1'],
    date: new Date(),
    object:{c: 2, d:{e: 3}},
    function: function(){
        return this.date;
    }
};

var copyObj = deepCopy(obj);

console.log('object comparison', copyObj === obj); //false
console.log('string check', copyObj.string === obj.string); //true
console.log('array check', copyObj.array === obj.array); //false
console.log('date check', copyObj2.date === obj.date); //false
console.log('object check', copyObj.object === obj.object); //false
console.log('function check', copyObj.function() === obj.function()); //true

How to sort findAll Doctrine's method?

It's useful to look at source code sometimes.

For example findAll implementation is very simple (vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php):

public function findAll()
{
    return $this->findBy(array());
}

So we look at findBy and find what we need (orderBy)

public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)

How to select top n rows from a datatable/dataview in ASP.NET

myDataTable.AsEnumerable().Take(5).CopyToDataTable()

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

Java "lambda expressions not supported at this language level"

Actually, Eclipse support for Java 8 is available: see here and here.

  • For Kepler, it is available as a "feature patch" against SR2 (i.e. Eclipse 4.3.2)
  • For Luna (Eclipse 4.4) it will be in the standard release. (release schedule)

PHP Include for HTML?

I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.

How to allow only numbers in textbox in mvc4 razor

DataType has a second constructor that takes a string. However, internally, this is actually the same as using the UIHint attribute.

Adding a new core DataType is not possible since the DataType enumeration is part of the .NET framework. The closest thing you can do is to create a new class that inherits from the DataTypeAttribute. Then you can add a new constructor with your own DataType enumeration.

public NewDataTypeAttribute(DataType dataType) : base(dataType)
 { }

public NewDataTypeAttribute(NewDataType newDataType) : base (newDataType.ToString();

You can also go through this link. But I will recommend you using Jquery for the same.

How to use code to open a modal in Angular 2?

This is one way I found. You can add a hidden button:

<button id="openModalButton" [hidden]="true" data-toggle="modal" data-target="#myModal">Open Modal</button>

Then use the code to "click" the button to open the modal:

document.getElementById("openModalButton").click();

This way can keep the bootstrap style of the modal and the fade in animation.

count (non-blank) lines-of-code in bash

The neatest command is

grep -vc ^$ fileName

with -c option, you don't even need wc -l

Explaining Apache ZooKeeper

I understand the ZooKeeper in general but had problems with the terms "quorum" and "split brain" so maybe I can share my findings with you (I consider myself also a layman).

Let's say we have a ZooKeeper cluster of 5 servers. One of the servers will become the leader and the others will become followers.

  • These 5 servers form a quorum. Quorum simply means "these servers can vote upon who should be the leader".

  • So the voting is based on majority. Majority simply means "more than half" so more than half of the number of servers must agree for a specific server to become the leader.

  • So there is this bad thing that may happen called "split brain". A split brain is simply this, as far as I understand: The cluster of 5 servers splits into two parts, or let's call it "server teams", with maybe one part of 2 and the other of 3 servers. This is really a bad situation as if both "server teams" must execute a specific order how would you decide wich team should be preferred? They might have received different information from the clients. So it is really important to know what "server team" is still relevant and which one can/should be ignored.

  • Majority is also the reason you should use an odd number of servers. If you have 4 servers and a split brain where 2 servers seperate then both "server teams" could say "hey, we want to decide who is the leader!" but how should you decide which 2 servers you should choose? With 5 servers it's simple: The server team with 3 servers has the majority and is allowed to select the new leader.

  • Even if you just have 3 servers and one of them fails the other 2 still form the majority and can agree that one of them will become the new leader.

I realize once you think about it some time and understand the terms it's not so complicated anymore. I hope this also helps anyone in understanding these terms.

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

How to Convert the value in DataTable into a string array in c#

If that's all what you want to do, you don't need to convert it into an array. You can just access it as:

string myData=yourDataTable.Rows[0][1].ToString();//Gives you USA

How to use log levels in java

The java.util.logging.Level documentation does a good job of defining when to use a log level and the target audience of that log level.

Most of the confusion with java.util.logging is in the tracing methods. It should be in the class level documentation but instead the Level.FINE field provides a good overview:

FINE is a message level providing tracing information. All of FINE, FINER, and FINEST are intended for relatively detailed tracing. The exact meaning of the three levels will vary between subsystems, but in general, FINEST should be used for the most voluminous detailed output, FINER for somewhat less detailed output, and FINE for the lowest volume (and most important) messages. In general the FINE level should be used for information that will be broadly interesting to developers who do not have a specialized interest in the specific subsystem. FINE messages might include things like minor (recoverable) failures. Issues indicating potential performance problems are also worth logging as FINE.

One important thing to understand which is not mentioned in the level documentation is that call-site tracing information is logged at FINER.

  • Logger#entering A LogRecord with message "ENTRY", log level FINER, ...
  • Logger#throwing The logging is done using the FINER level...The LogRecord's message is set to "THROW"
  • Logger#exiting A LogRecord with message "RETURN", log level FINER...

If you log a message as FINE you will be able to configure logging system to see the log output with or without tracing log records surrounding the log message. So use FINE only when tracing log records are not required as context to understand the log message.

FINER indicates a fairly detailed tracing message. By default logging calls for entering, returning, or throwing an exception are traced at this level.

In general, most use of FINER should be left to call of entering, exiting, and throwing. That will for the most part reserve FINER for call-site tracing when verbose logging is turned on. When swallowing an expected exception it makes sense to use FINER in some cases as the alternative to calling trace throwing method since the exception is not actually thrown. This makes it look like a trace when it isn't a throw or an actual error that would be logged at a higher level.

FINEST indicates a highly detailed tracing message.

Use FINEST when the tracing log message you are about to write requires context information about program control flow. You should also use FINEST for tracing messages that produce large amounts of output data.

CONFIG messages are intended to provide a variety of static configuration information, to assist in debugging problems that may be associated with particular configurations. For example, CONFIG message might include the CPU type, the graphics depth, the GUI look-and-feel, etc.

The CONFIG works well for assisting system admins with the items listed above.

Typically INFO messages will be written to the console or its equivalent. So the INFO level should only be used for reasonably significant messages that will make sense to end users and system administrators.

Examples of this are tracing program startup and shutdown.

In general WARNING messages should describe events that will be of interest to end users or system managers, or which indicate potential problems.

An example use case could be exceptions thrown from AutoCloseable.close implementations.

In general SEVERE messages should describe events that are of considerable importance and which will prevent normal program execution. They should be reasonably intelligible to end users and to system administrators.

For example, if you have transaction in your program where if any one of the steps fail then all of the steps voided then SEVERE would be appropriate to use as the log level.

No matching bean of type ... found for dependency

I had a similar issue but I was missing the (@Service or @Component) from the implementation of com.example.my.services.myUser.MyUserServiceImpl

How to import a JSON file in ECMAScript 6?

Simply do this:

import * as importedConfig from '../config.json';

Then use it like the following:

const config = importedConfig.default;

Unable to access JSON property with "-" dash

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]

javascript: calculate x% of a number

In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:

function calculatePercent(amount, percent) {
    const amountDecimals = getNumberOfDecimals(amount);
    const percentDecimals = getNumberOfDecimals(percent);
    const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
    const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
    const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`;    // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)

    return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
}

function getNumberOfDecimals(number) {
    const decimals = parseFloat(number).toString().split('.')[1];

    if (decimals) {
        return decimals.length;
    }

    return 0;
}

calculatePercent(20.05, 10); // 2.005

As you can see, I:

  1. Count the number of decimals in both the amount and the percent
  2. Convert both amount and percent to integers using exponential notation
  3. Calculate the exponential notation needed to determine the proper end value
  4. Calculate the end value

The usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.

Plotting a fast Fourier transform in Python

So I run a functionally equivalent form of your code in an IPython notebook:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)

fig, ax = plt.subplots()
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
plt.show()

I get what I believe to be very reasonable output.

enter image description here

It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue?

In response to the raw data and comments being posted

The problem here is that you don't have periodic data. You should always inspect the data that you feed into any algorithm to make sure that it's appropriate.

import pandas
import matplotlib.pyplot as plt
#import seaborn
%matplotlib inline

# the OP's data
x = pandas.read_csv('http://pastebin.com/raw.php?i=ksM4FvZS', skiprows=2, header=None).values
y = pandas.read_csv('http://pastebin.com/raw.php?i=0WhjjMkb', skiprows=2, header=None).values
fig, ax = plt.subplots()
ax.plot(x, y)

enter image description here

How to debug .htaccess RewriteRule not working

To test your htaccess rewrite rules, simply fill in the url that you're applying the rules to, place the contents of your htaccess on the larger input area and press "Test" button.

http://htaccess.mwl.be/

How to add a new column to a CSV file?

I'm surprised no one suggested Pandas. Although using a set of dependencies like Pandas might seem more heavy-handed than is necessary for such an easy task, it produces a very short script and Pandas is a great library for doing all sorts of CSV (and really all data types) data manipulation. Can't argue with 4 lines of code:

import pandas as pd
csv_input = pd.read_csv('input.csv')
csv_input['Berries'] = csv_input['Name']
csv_input.to_csv('output.csv', index=False)

Check out Pandas Website for more information!

Contents of output.csv:

Name,Code,Berries
blackberry,1,blackberry
wineberry,2,wineberry
rasberry,1,rasberry
blueberry,1,blueberry
mulberry,2,mulberry

Converting HTML to Excel?

So long as Excel can open the file, the functionality to change the format of the opened file is built in.

To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub

Check whether number is even or odd

package isevenodd;
import java.util.Scanner;
public class IsEvenOdd {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter number: ");
        int y = scan.nextInt();       
        boolean isEven = (y % 2 == 0) ? true : false;
        String x = (isEven) ? "even" : "odd";  
        System.out.println("Your number is " + x);
    }
}

Xcode 6.1 - How to uninstall command line tools?

If you installed the command line tools separately, delete them using:

sudo rm -rf /Library/Developer/CommandLineTools

How to exit from the application and show the home screen?

Add following lines after finish(); in onDestroy():

android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();

Apache HttpClient Android (Gradle)

I searched over and over this solution works like a charm ::

    apply plugin: 'com.android.application'
    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.3"
        defaultConfig {
            applicationId "com.anzma.memories"
            useLibrary 'org.apache.http.legacy'
            minSdkVersion 15
            targetSdkVersion 25
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
 packagingOptions {
            exclude 'META-INF/DEPENDENCIES.txt'
            exclude 'META-INF/LICENSE.txt'
            exclude 'META-INF/NOTICE.txt'
            exclude 'META-INF/NOTICE'
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/DEPENDENCIES'
            exclude 'META-INF/notice.txt'
            exclude 'META-INF/license.txt'
            exclude 'META-INF/dependencies.txt'
            exclude 'META-INF/LGPL2.1'
        }
    buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile('org.apache.httpcomponents:httpmime:4.3.6') {
            exclude module: 'httpclient'
        }
        compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
        compile 'com.android.support:appcompat-v7:25.3.1'
        testCompile 'junit:junit:4.12'
    }

How can I String.Format a TimeSpan object with a custom format in .NET?

This is a pain in VS 2010, here's my workaround solution.

 public string DurationString
        {
            get 
            {
                if (this.Duration.TotalHours < 24)
                    return new DateTime(this.Duration.Ticks).ToString("HH:mm");
                else //If duration is more than 24 hours
                {
                    double totalminutes = this.Duration.TotalMinutes;
                    double hours = totalminutes / 60;
                    double minutes = this.Duration.TotalMinutes - (Math.Floor(hours) * 60);
                    string result = string.Format("{0}:{1}", Math.Floor(hours).ToString("00"), Math.Floor(minutes).ToString("00"));
                    return result;
                }
            } 
        }

RecyclerView inside ScrollView is not working

use NestedScrollView instead of ScrollView

Please go through NestedScrollView reference document for more information.

and add recyclerView.setNestedScrollingEnabled(false); to your RecyclerView

How to remove duplicates from a list?

IMHO best way how to do it these days:

Suppose you have a Collection "dups" and you want to create another Collection containing the same elements but with all duplicates eliminated. The following one-liner does the trick.

Collection<collectionType> noDups = new HashSet<collectionType>(dups);

It works by creating a Set which, by definition, cannot contain duplicates.

Based on oracle doc.

Android ImageView Animation

Verified Code:

imageView.setImageResource(R.drawable.ic_arrow_up);

boolean up = true;

if (!up) { 
    up = true; 
    imageView.startAnimation(animate(up)); 
} else { 
    up = false; 
    imageView.startAnimation(animate(up)); 
}

private Animation animate(boolean up) {
    Animation anim = AnimationUtils.loadAnimation(this, up ? R.anim.rotate_up : R.anim.rotate_down);
    anim.setInterpolator(new LinearInterpolator()); // for smooth animation
    return anim;
}

drawable/ic_arrow_up.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#3d3d3d"
        android:pathData="M7.41,15.41L12,10.83l4.59,4.58L18,14l-6,-6 -6,6z"/>
</vector>

anim/rotate_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:fillEnabled="true">
    <rotate
        android:duration="200"
        android:fromDegrees="-180"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="0" />
</set>

anim/rotate_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:fillEnabled="true">
    <rotate
        android:duration="200"
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="180" />
</set>

How to use ArrayList's get() method

Would this help?

final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));

Why is "using namespace std;" considered bad practice?

One shouldn't use the using directive at the global scope, especially in headers. However, there are situations where it is appropriate even in a header file:

template <typename FloatType> inline
FloatType compute_something(FloatType x)
{
    using namespace std; // No problem since scope is limited
    return exp(x) * (sin(x) - cos(x * 2) + sin(x * 3) - cos(x * 4));
}

This is better than explicit qualification (std::sin, std::cos...), because it is shorter and has the ability to work with user defined floating point types (via argument-dependent lookup (ADL)).

How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

Keep in mind that if you want to use the chrome inspect in Windows, besides enabling usb debugging on you mobile, you should also install the usb driver for Windows.

You can find the drivers you need from the list here:

http://androidxda.com/download-samsung-usb-drivers

Furthermore, you should use a newer version of Chrome mobile than the one in your Desktop.

Count number of objects in list

length(x)

Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.

lengths(x)

Get the length of each element of a list or atomic vector (is.atomic) as an integer or numeric vector.

Rounded corner for textview in android

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dp" />
            <solid android:color="#ffffff"/>

        </shape>
    </item>
</layer-list>

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

github markdown colspan

You can use HTML tables on GitHub (but not on StackOverflow)

<table>
  <tr>
    <td>One</td>
    <td>Two</td>
  </tr>
  <tr>
    <td colspan="2">Three</td>
  </tr>
</table>

Becomes

HTML table output

Determine path of the executing script

I couldn't get Suppressingfire's solution to work when 'source'ing from the R console.
I couldn't get hadley's solution to work when using Rscript.

Best of both worlds?

thisFile <- function() {
        cmdArgs <- commandArgs(trailingOnly = FALSE)
        needle <- "--file="
        match <- grep(needle, cmdArgs)
        if (length(match) > 0) {
                # Rscript
                return(normalizePath(sub(needle, "", cmdArgs[match])))
        } else {
                # 'source'd via R console
                return(normalizePath(sys.frames()[[1]]$ofile))
        }
}

Uploading a file in Rails

Sept 2018

For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.

Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)

Paperclip team deprecated the gem in favor of the Rails ActiveStorage.

Here is the github page for the ActiveStorage & plenty of resources are available everywhere

Also I found this video to be very helpful to understand the features of Activestorage

Regex to match any character including new lines

You want to use "multiline".

$string =~ /(START)(.+?)(END)/m;

How to count TRUE values in a logical vector

There are some problems when logical vector contains NA values.
See for example:

z <- c(TRUE, FALSE, NA)
sum(z) # gives you NA
table(z)["TRUE"] # gives you 1
length(z[z == TRUE]) # f3lix answer, gives you 2 (because NA indexing returns values)

So I think the safest is to use na.rm = TRUE:

sum(z, na.rm = TRUE) # best way to count TRUE values

(which gives 1). I think that table solution is less efficient (look at the code of table function).

Also, you should be careful with the "table" solution, in case there are no TRUE values in the logical vector. Suppose z <- c(NA, FALSE, NA) or simply z <- c(FALSE, FALSE), then table(z)["TRUE"] gives you NA for both cases.

How can I list all the deleted files in a Git repository?

git log --diff-filter=D --summary

See Find and restore a deleted file in a Git repository

If you don't want all the information about which commit they were removed in, you can just add a grep delete in there.

git log --diff-filter=D --summary | grep delete

Is there a way to get the git root directory in one command?

Pre-Configured Shell Aliases in Shell Frameworks

If you use a shell framework, there might already be a shell alias available:

  • $ grt in oh-my-zsh (68k) (cd $(git rev-parse --show-toplevel || echo "."))
  • $ git-root in prezto (8.8k) (displays the path to the working tree root)
  • $ g.. zimfw (1k) (changes the current directory to the top level of the working tree.)

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

Open soft keyboard programmatically

Kotlin

fun hideKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

Java

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}

Forcing Internet Explorer 9 to use standards document mode

put a doctype as the first line of your html document

<!DOCTYPE html>

you can find detailed explanation about internet explorer document compatibility here: Defining Document Compatibility

jQuery 'each' loop with JSON array

Try (untested):

$.getJSON("data.php", function(data){
    $.each(data.justIn, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.recent, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.old, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });    
});

I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:

$.getJSON("data.php", function(data){
    $.each(data, function(k, v) {
        alert(k + ' ' + v);
        $.each(v, function(k1, v1) {
            alert(k1 + ' ' + v1);
        });
    });
}); 

How to return a value from a Form in C#?

First you have to define attribute in form2(child) you will update this attribute in form2 and also from form1(parent) :

 public string Response { get; set; }

 private void OkButton_Click(object sender, EventArgs e)
 {
    Response = "ok";
 }

 private void CancelButton_Click(object sender, EventArgs e)
 {
    Response = "Cancel";
 }

Calling of form2(child) from form1(parent):

  using (Form2 formObject= new Form2() )
  {
     formObject.ShowDialog();

      string result = formObject.Response; 
      //to update response of form2 after saving in result
      formObject.Response="";

      // do what ever with result...
      MessageBox.Show("Response from form2: "+result); 
  }

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

From the Errata: ModelState.AddRuleViolations(dinner.GetRuleViolations());

Should be:

ModelState.AddModelErrors(dinner.GetRuleViolations());

Reference: http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-MVC-1-0.productCd-0470384611,descCd-ERRATA.html

PowerShell Connect to FTP server and get files

Here is the full working code to download all files (with wildcard or file extension) from the FTP site to local directory. Set the variable values.

    #FTP Server Information - SET VARIABLES
    $ftp = "ftp://XXX.com/" 
    $user = 'UserName' 
    $pass = 'Password'
    $folder = 'FTP_Folder'
    $target = "C:\Folder\Folder1\"

    #SET CREDENTIALS
    $credentials = new-object System.Net.NetworkCredential($user, $pass)

    function Get-FtpDir ($url,$credentials) {
        $request = [Net.WebRequest]::Create($url)
        $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
        if ($credentials) { $request.Credentials = $credentials }
        $response = $request.GetResponse()
        $reader = New-Object IO.StreamReader $response.GetResponseStream() 
        while(-not $reader.EndOfStream) {
            $reader.ReadLine()
        }
        #$reader.ReadToEnd()
        $reader.Close()
        $response.Close()
    }

    #SET FOLDER PATH
    $folderPath= $ftp + "/" + $folder + "/"

    $files = Get-FTPDir -url $folderPath -credentials $credentials

    $files 

    $webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
    $counter = 0
    foreach ($file in ($files | where {$_ -like "*.txt"})){
        $source=$folderPath + $file  
        $destination = $target + $file 
        $webclient.DownloadFile($source, $target+$file)

        #PRINT FILE NAME AND COUNTER
        $counter++
        $counter
        $source
    }

How to execute a Windows command on a remote PC?

psexec \\RemoteComputer cmd.exe

or use ssh or TeamViewer or RemoteDesktop!

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

Failure [INSTALL_FAILED_USER_RESTRICTED: Install canceled by user]:

Go to Settings->Additional Settings->Developer options->Developer Option(Need to enable)->USB debugging(Need to enable)->Install via USB (Need to enable)->USB debugging (Security settings)(Need to enable)

Perfectly working in the above steps.

Enjoy your coding...

Forward host port to docker container

A simple but relatively insecure way would be to use the --net=host option to docker run.

This option makes it so that the container uses the networking stack of the host. Then you can connect to services running on the host simply by using "localhost" as the hostname.

This is easier to configure because you won't have to configure the service to accept connections from the IP address of your docker container, and you won't have to tell the docker container a specific IP address or host name to connect to, just a port.

For example, you can test it out by running the following command, which assumes your image is called my_image, your image includes the telnet utility, and the service you want to connect to is on port 25:

docker run --rm -i -t --net=host my_image telnet localhost 25

If you consider doing it this way, please see the caution about security on this page:

https://docs.docker.com/articles/networking/

It says:

--net=host -- Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick ip addr command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does not let the container reconfigure the host network stack — that would require --privileged=true — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like restart your computer. You should use this option with caution.

What is the 'new' keyword in JavaScript?

so it's probably not for creating instances of object

It's used exactly for that. You define a function constructor like so:

function Person(name) {
    this.name = name;
}

var john = new Person('John');

However the extra benefit that ECMAScript has is you can extend with the .prototype property, so we can do something like...

Person.prototype.getName = function() { return this.name; }

All objects created from this constructor will now have a getName because of the prototype chain that they have access to.

Remove the last character in a string in T-SQL?

I can suggest this -hack- ;).

select 
    left(txt, abs(len(txt + ',') - 2))
from 
    t;

SQL Server Fiddle Demo

Use component from another module

SOLVED HOW TO USE A COMPONENT DECLARED IN A MODULE IN OTHER MODULE.

Based on Royi Namir explanation (Thank you so much). There is a missing part to reuse a component declared in a Module in any other module while lazy loading is used.

1st: Export the component in the module which contains it:

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  exports: [TaskCardComponent] <== this line
})
export class TaskModule{}

2nd: In the module where you want to use TaskCardComponent:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdCardModule } from '@angular2-material/card';

@NgModule({
  imports: [
   CommonModule,
   MdCardModule
   ],
  providers: [],
  exports:[ MdCardModule ] <== this line
})
export class TaskModule{}

Like this the second module imports the first module which imports and exports the component.

When we import the module in the second module we need to export it again. Now we can use the first component in the second module.

Table overflowing outside of div

A crude work around is to set display: table on the containing div.

How to calculate age in T-SQL with years, months, and days

declare @BirthDate datetime
declare @TotalYear int
declare @TotalMonths int
declare @TotalDays int
declare @TotalWeeks int
declare @TotalHours int
declare @TotalMinute int
declare @TotalSecond int
declare @CurrentDtTime datetime
set @BirthDate='1998/01/05 05:04:00'  -- Set Your date here
set @TotalYear= FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) / 365.25)
set @TotalMonths= FLOOR(DATEDIFF(DAY,DATEADD(year, @TotalYear,@BirthDate),GetDate()) / 30.436875E)
set @TotalDays= FLOOR(DATEDIFF(DAY, DATEADD(month, @TotalMonths,DATEADD(year, 
    @TotalYear,@BirthDate)), GETDATE()))
set @CurrentDtTime=CONVERT(datetime,CONVERT(varchar(50), DATEPART(year, 
    GetDate()))+'/' +CONVERT(varchar(50), DATEPART(MONTH, GetDate()))
    +'/'+ CONVERT(varchar(50),DATEPART(DAY, GetDate()))+' '
    + CONVERT(varchar(50),DATEPART(HOUR, @BirthDate))+':'+ 
     CONVERT(varchar(50),DATEPART(MINUTE, @BirthDate))+
   ':'+ CONVERT(varchar(50),DATEPART(Second, @BirthDate)))
set @TotalHours = DATEDIFF(hour, @CurrentDtTime, GETDATE())
if(@TotalHours < 0)
begin
   set @TotalHours = DATEDIFF(hour,DATEADD(Day,-1, @CurrentDtTime), GETDATE())
   set @TotalDays= @TotalDays -1  
 end
set @TotalMinute= DATEPART(MINUTE, GETDATE())-DATEPART(MINUTE, @BirthDate)
 if(@TotalMinute < 0)
set @TotalMinute = DATEPART(MINUTE, DATEADD(hour,-1,GETDATE()))+(60-DATEPART(MINUTE, 
   @BirthDate))

set @TotalSecond= DATEPART(Second, GETDATE())-DATEPART(Second, @BirthDate)

 Print 'Your age are'+ CHAR(13)
 + CONVERT(varchar(50), @TotalYear)+' Years, ' +
   CONVERT(varchar(50),@TotalMonths) +' Months, ' +
   CONVERT(varchar(50),@TotalDays)+' Days, ' +
   CONVERT(varchar(50),@TotalHours)+' Hours, ' +
   CONVERT(varchar(50),@TotalMinute)+' Minutes, ' + 
   CONVERT(varchar(50),@TotalSecond)+' Seconds. ' +char(13)+
     'Your are born at day of week was - ' + CONVERT(varchar(50),DATENAME(dw , 
     @BirthDate ))
  +char(13)+char(13)+
+'Your Birthdate to till date your '+ CHAR(13)
+'Years - ' + CONVERT(varchar(50), FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) / 
   365.25))
+' , Months - ' + CONVERT(varchar(50),DATEDIFF(MM,@BirthDate,getdate())) 
+' , Weeks - ' + CONVERT(varchar(50),DATEDIFF(wk,@BirthDate,getdate()))
+' , Days - ' + CONVERT(varchar(50),DATEDIFF(dd,@BirthDate,getdate()))+char(13)+
+'Hours - ' + CONVERT(varchar(50),DATEDIFF(HH,@BirthDate,getdate()))
+' , Minutes - ' + CONVERT(varchar(50),DATEDIFF(mi,@BirthDate,getdate()))
+' , Seconds - ' + CONVERT(varchar(50),DATEDIFF(ss,@BirthDate,getdate()))

Output

Your age are
22 Years, 0 Months, 2 Days, 11 Hours, 30 Minutes, 16 Seconds. 
Your are born at day of week was - Monday

Your Birthdate to till date your 
Years - 22 , Months - 264 , Weeks - 1148 , Days - 8037
Hours - 192899 , Minutes - 11573970 , Seconds - 694438216

How to create virtual column using MySQL SELECT?

Something like:

SELECT id, email, IF(active = 1, 'enabled', 'disabled') AS account_status FROM users

This allows you to make operations and show it as columns.

EDIT:

you can also use joins and show operations as columns:

SELECT u.id, e.email, IF(c.id IS NULL, 'no selected', c.name) AS country
FROM users u LEFT JOIN countries c ON u.country_id = c.id

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.