Programs & Examples On #Ws security

WS-Security is an extension to SOAP for applying security to web-services through XML Signature and XML Encryption.

How to add soap header in java

I struggled to get this working. That's why I'll add a complete solution here:

My objective is to add this header to the SOAP envelope:

   <soapenv:Header>
      <urn:OTAuthentication>
         <urn:AuthenticationToken>TOKEN</urn:AuthenticationToken>
      </urn:OTAuthentication>
   </soapenv:Header>
  1. First create a SOAPHeaderHandler class.

    import java.util.Set;
    import java.util.TreeSet;
    
    import javax.xml.namespace.QName;
    import javax.xml.soap.SOAPElement;
    import javax.xml.soap.SOAPEnvelope;
    import javax.xml.soap.SOAPFactory;
    import javax.xml.soap.SOAPHeader;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.handler.soap.SOAPHandler;
    import javax.xml.ws.handler.soap.SOAPMessageContext;
    
    public class SOAPHeaderHandler implements SOAPHandler<SOAPMessageContext> {
    
        private final String authenticatedToken;
    
        public SOAPHeaderHandler(String authenticatedToken) {
            this.authenticatedToken = authenticatedToken;
        }
    
        public boolean handleMessage(SOAPMessageContext context) {
            Boolean outboundProperty =
                    (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (outboundProperty.booleanValue()) {
                try {
                    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                    SOAPFactory factory = SOAPFactory.newInstance();
                    String prefix = "urn";
                    String uri = "urn:api.ecm.opentext.com";
                    SOAPElement securityElem =
                            factory.createElement("OTAuthentication", prefix, uri);
                    SOAPElement tokenElem =
                            factory.createElement("AuthenticationToken", prefix, uri);
                    tokenElem.addTextNode(authenticatedToken);
                    securityElem.addChildElement(tokenElem);
                    SOAPHeader header = envelope.addHeader();
                    header.addChildElement(securityElem);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // inbound
            }
            return true;
        }
    
        public Set<QName> getHeaders() {
            return new TreeSet();
        }
    
        public boolean handleFault(SOAPMessageContext context) {
            return false;
        }
    
        public void close(MessageContext context) {
            //
        }
    }
    
    1. Add the handler to the proxy. Note that according javax.xml.ws.Binding's documentation: "If the returned chain is modified a call to setHandlerChain is required to configure the binding instance with the new chain."

    Authentication_Service authentication_Service = new Authentication_Service();

    Authentication basicHttpBindingAuthentication = authentication_Service.getBasicHttpBindingAuthentication(); String authenticatedToken = "TOKEN"; List<Handler> handlerChain = ((BindingProvider)basicHttpBindingAuthentication).getBinding().getHandlerChain(); handlerChain.add(new SOAPHeaderHandler(authenticatedToken)); ((BindingProvider)basicHttpBindingAuthentication).getBinding().setHandlerChain(handlerChain);

JAX-WS - Adding SOAP Headers

I struggled with all the answers here, starting with Pascal's solution, which is getting harder with the Java compiler not binding against rt.jar by default any more (and using internal classes makes it specific to that runtime implementation).

The answer from edubriguenti brought me close. The way the handler is hooked up in the final bit of code didn't work for me, though - it was never called.

I ended up using a variation of his handler class, but wired it into the javax.xml.ws.Service instance like this:

Service service = Service.create(url, qname); service.setHandlerResolver( portInfo -> Collections.singletonList(new SOAPHeaderHandler(handlerArgs)) );

Example of SOAP request authenticated with WS-UsernameToken

The Hash Password Support and Token Assertion Parameters in Metro 1.2 explains very nicely what a UsernameToken with Digest Password looks like:

Digest Password Support

The WSS 1.1 Username Token Profile allows digest passwords to be sent in a wsse:UsernameToken of a SOAP message. Two more optional elements are included in the wsse:UsernameToken in this case: wsse:Nonce and wsse:Created. A nonce is a random value that the sender creates to include in each UsernameToken that it sends. A creation time is added to combine nonces to a "freshness" time period. The Password Digest in this case is calculated as:

Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )

This is how a UsernameToken with Digest Password looks like:

<wsse:UsernameToken wsu:Id="uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c">
   <wsse:Username>Alice</wsse:Username>
   <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6S3P2EWNP3lQf+9VC3emNoT57oQ=</wsse:Password>
   <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">YF6j8V/CAqi+1nRsGLRbuZhi</wsse:Nonce>
   <wsu:Created>2008-04-28T10:02:11Z</wsu:Created>
</wsse:UsernameToken>

How to read one single line of csv data in Python?

You can use Pandas library to read the first few lines from the huge dataset.

import pandas as pd

data = pd.read_csv("names.csv", nrows=1)

You can mention the number of lines to be read in the nrows parameter.

Check whether an array is empty

However, empty($error) still returns true, even though nothing is set.

That's not how empty() works. According to the manual, it will return true on an empty array only. Anything else wouldn't make sense.

Spring jUnit Testing properties file

I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:

Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);

How do I replace text in a selection?

As @JOPLOmacedo stated, ctrl + F is what you need, but if you can't use that shortcut you can check in menu:

  • Find -> Find..

    and there you have it.
    You can also set a custom keybind for Find going in:

  • Preferences -> Key Bindings - User

    As your request for the selection only request, there is a button right next to the search field where you can opt-in for "in selection".

  • How I can check if an object is null in ruby on rails 2?

    You can check if an object is nil (null) by calling present? or blank? .

    @object.present?
    

    this will return false if the project is an empty string or nil .

    or you can use

    @object.blank?
    

    this is the same as present? with a bang and you can use it if you don't like 'unless'. this will return true for an empty string or nil .

    How can I check if the current date/time is past a set date/time?

    Since PHP >= 5.2.2 you can use the DateTime class as such:

    if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
        # current time is greater than 2010-05-15 16:00:00
        # in other words, 2010-05-15 16:00:00 has passed
    }
    

    The string passed to the DateTime constructor is parsed according to these rules.


    Note that it is also possible to use time and strtotime functions. See original answer.

    Error: expected type-specifier before 'ClassName'

    First of all, let's try to make your code a little simpler:

    // No need to create a circle unless it is clearly necessary to
    // demonstrate the problem
    
    // Your Rect2f defines a default constructor, so let's use it for simplicity.
    shared_ptr<Shape> rect(new Rect2f());
    

    Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

    int main() {
        delete new T();
    }
    

    This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

    In function 'int main()':
    Line 2: error: expected type-specifier before 'T'
    

    Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

    How do you specify a debugger program in Code::Blocks 12.11?

    1. Go to settings >> Debugger.
    2. Now as you can see in the image below. There's a tree. Common->GDB/CDB Debugger -> Default. enter image description here

    3. Click on executable path (on the right) to find the address to gdb32.exe .

    4. Click gdb32.exe >> OK.

    THATS IT!! This worked for me.

    Deleting a pointer in C++

    Pointers are similar to normal variables in that you don't need to delete them. They are removed from memory at the end of a functions execution and/or the end of the program.

    You can however use pointers to allocate a 'block' of memory, for example like this:

    int *some_integers = new int[20000]
    

    This will allocate memory space for 20000 integers. Useful, because the Stack has a limited size and you might want to mess about with a big load of 'ints' without a stack overflow error.

    Whenever you call new, you should then 'delete' at the end of your program, because otherwise you will get a memory leak, and some allocated memory space will never be returned for other programs to use. To do this:

    delete [] some_integers;
    

    Hope that helps.

    Can't concat bytes to str

    f.write(plaintext)
    f.write("\n".encode("utf-8"))
    

    Execute ssh with password authentication via windows command prompt

    PuTTY's plink has a command-line argument for a password. Some other suggestions have been made in the answers to this question: using Expect (which is available for Windows), or writing a launcher in Python with Paramiko.

    How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

    If your data file is structured like this

    col1, col2, col3
       1,    2,    3
      10,   20,   30
     100,  200,  300
    

    then numpy.genfromtxt can interpret the first line as column headers using the names=True option. With this you can access the data very conveniently by providing the column header:

    data = np.genfromtxt('data.txt', delimiter=',', names=True)
    print data['col1']    # array([   1.,   10.,  100.])
    print data['col2']    # array([   2.,   20.,  200.])
    print data['col3']    # array([   3.,   30.,  300.])
    

    Since in your case the data is formed like this

    row1,   1,  10, 100
    row2,   2,  20, 200
    row3,   3,  30, 300
    

    you can achieve something similar using the following code snippet:

    labels = np.genfromtxt('data.txt', delimiter=',', usecols=0, dtype=str)
    raw_data = np.genfromtxt('data.txt', delimiter=',')[:,1:]
    data = {label: row for label, row in zip(labels, raw_data)}
    

    The first line reads the first column (the labels) into an array of strings. The second line reads all data from the file but discards the first column. The third line uses dictionary comprehension to create a dictionary that can be used very much like the structured array which numpy.genfromtxt creates using the names=True option:

    print data['row1']    # array([   1.,   10.,  100.])
    print data['row2']    # array([   2.,   20.,  200.])
    print data['row3']    # array([   3.,   30.,  300.])
    

    Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

    No. Mostly because it's of a rather niche need, and there are too many possible variations. (Is it "KB", "Kb" or "Ko"? Is a megabyte 1024 * 1024 bytes, or 1024 * 1000 bytes? -- yes, some places use that!)

    How can I add an item to a SelectList in ASP.net MVC

    I liked @AshOoO's answer but like @Rajan Rawal I needed to preserve selected item state, if any. So I added my customization to his method AddFirstItem()

    public static SelectList AddFirstItem(SelectList origList, SelectListItem firstItem)
    {
        List<SelectListItem> newList = origList.ToList();
        newList.Insert(0, firstItem);
    
        var selectedItem = newList.FirstOrDefault(item => item.Selected);
        var selectedItemValue = String.Empty;
        if (selectedItem != null)
        {
            selectedItemValue = selectedItem.Value;
        }
    
        return new SelectList(newList, "Value", "Text", selectedItemValue);
    }
    

    Setting default permissions for newly created files and sub-directories under a directory in Linux?

    in your shell script (or .bashrc) you may use somthing like:

    umask 022

    umask is a command that determines the settings of a mask that controls how file permissions are set for newly created files.

    Generic XSLT Search and Replace template

    Here's one way in XSLT 2

    <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

    Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

    What are named pipes?

    Compare

    echo "test" | wc
    

    to

    mkdnod apipe p
    wc apipe
    

    wc will block until

    echo "test" > apipe
    

    executes

    Can I install the "app store" in an IOS simulator?

    No, according to Apple here:

    Note: You cannot install apps from the App Store in simulation environments.

    Unit Testing: DateTime.Now

    Moles:

    [Test]  
    public void TestOfDateTime()  
    {  
          var firstValue = DateTime.Now;
          MDateTime.NowGet = () => new DateTime(2000,1,1);
          var secondValue = DateTime.Now;
          Assert(firstValue > secondValue); // would be false if 'moleing' failed
    }
    

    Disclaimer - I work on Moles

    SQLite Query in Android to count rows

    int nombr = 0;
    Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
    nombr = cursor.getCount();
    

    Show div #id on click with jQuery

    This is simple way to Display Div using:-

    $("#musicinfo").show();  //or
    $("#musicinfo").css({'display':'block'});  //or
    $("#musicinfo").toggle("slow");   //or
    $("#musicinfo").fadeToggle();    //or
    

    Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

    This MSDN thread explains how to fix it.

    To summarize:

    • Either disable incremental linking, by going to

      Project Properties 
         -> Configuration Properties 
             -> Linker (General) 
                -> Enable Incremental Linking -> "No (/INCREMENTAL:NO)"
      
    • or install VS2010 SP1.

    Edits (@CraigRinger): Note that installing VS 2010 SP1 will remove the 64-bit compilers. You need to install the VS 2010 SP1 compiler pack to get them back.

    This affects Microsoft Windows SDK 7.1 for Windows 7 and .NET 4.0 as well as Visual Studio 2010.

    How to calculate the number of occurrence of a given character in each row of a column of strings?

    The stringr package provides the str_count function which seems to do what you're interested in

    # Load your example data
    q.data<-data.frame(number=1:3, string=c("greatgreat", "magic", "not"), stringsAsFactors = F)
    library(stringr)
    
    # Count the number of 'a's in each element of string
    q.data$number.of.a <- str_count(q.data$string, "a")
    q.data
    #  number     string number.of.a
    #1      1 greatgreat           2
    #2      2      magic           1
    #3      3        not           0
    

    Oracle Error ORA-06512

    ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).

    In a comment you said

    "still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"

    Well, your code does this:

    IF ((pNum < 12) OR (pNum > 14)) THEN     
        RAISE vSOME_EX;
    

    That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?

    ORA-06510: PL/SQL: unhandled user-defined exception

    If so, all you need to do is add an exception block to handle the error. Perhaps:

    PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
    AS
        vSOME_EX EXCEPTION;
    
    BEGIN 
        IF ((pNum < 12) OR (pNum > 14)) THEN     
            RAISE vSOME_EX;
        ELSE  
            EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
        END IF;
    exception
        when vsome_ex then
             raise_application_error(-20000
                                     , 'This is not a valid table:  M'||pNum||'GR');
    
    END PX;
    

    The documentation covers handling PL/SQL exceptions in depth.

    Bash mkdir and subfolders

    To create multiple sub-folders

    mkdir -p parentfolder/{subfolder1,subfolder2,subfolder3}
    

    Loading a .json file into c# program

    Use Server.MapPath to get the actual path of the JSON file and load and read the file using StreamReader

    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    
    public class RootObject
    {
        public string url_short { get; set; }
        public string url_long { get; set; }
        public int type { get; set; }
    }
    
    public class Program
    {
        static public void Main()
        {
           using (StreamReader r = new StreamReader(Server.MapPath("~/test.json")))
           {
               string json = r.ReadToEnd();
               List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
           }
    
        Console.WriteLine(ro[0].url_short);                 
        }  
    }
    

    Note : Look below link also I have answered for question similar to this.It will be help full for you How to Parse an example string in C#

    How can I make grep print the lines below and above each matching line?

    Use -A and -B switches (mean lines-after and lines-before):

    grep -A 1 -B 1 FAILED file.txt
    

    json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

    This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

    string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
    

    My solution to this would be to use the string.replace() to convert these items to a string:

    import json
    
    string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
    
    string = string.replace("False", '"False"')
    
    dict_list = json.loads(string)
    

    How to set default text for a Tkinter Entry widget

    Use Entry.insert. For example:

    try:
        from tkinter import *  # Python 3.x
    except Import Error:
        from Tkinter import *  # Python 2.x
    
    root = Tk()
    e = Entry(root)
    e.insert(END, 'default text')
    e.pack()
    root.mainloop()
    

    Or use textvariable option:

    try:
        from tkinter import *  # Python 3.x
    except Import Error:
        from Tkinter import *  # Python 2.x
    
    root = Tk()
    v = StringVar(root, value='default text')
    e = Entry(root, textvariable=v)
    e.pack()
    root.mainloop()
    

    How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

    I've created config/initializers/secret_key.rb file and I wrote only following line of code:

    Rails.application.config.secret_key_base = ENV["SECRET_KEY_BASE"]
    

    But I think that solution posted by @Erik Trautman is more elegant ;)

    Edit: Oh, and finally I found this advice on Heroku: https://devcenter.heroku.com/changelog-items/426 :)

    Enjoy!

    GCM with PHP (Google Cloud Messaging)

    After searching for a long time finally I am able to figure out what I exactly needed, Connecting to the GCM using PHP as a server side scripting language, The following tutorial will give us a clear idea of how to setup everything we need to get started with GCM

    Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL

    Carousel with Thumbnails in Bootstrap 3.0

    Just found out a great plugin for this:

    http://flexslider.woothemes.com/

    Regards

    jQuery or JavaScript auto click

    First i tried with this sample code:

    $(document).ready(function(){ 
         $('#upload-file').click(); 
    });
    

    It didn't work for me. Then after, tried with this

    $(document).ready(function(){ 
         $('#upload-file')[0].click(); 
    });
    

    No change. At last, tried with this

    $(document).ready(function(){ 
         $('#upload-file')[0].click(function(){
         }); 
    });
    

    Solved my problem. Helpful for anyone.

    Chrome DevTools Devices does not detect device when plugged in

    There is a necessary step which is not detailed:

    ADB must be running (it is not because it is installed that it will run to establish the connection)

    For an unknown reason to open "developer tools" on chrome (canary) will not necessarily launch the run of ADB with good parameters. Then you will not see on the smartphone the question "Confirm remote connection with 'your pc address' " while on PC you can see on the connection panel "pending unknown connection". Then necessarily if this not happens the connection will not be established. Note that some other tools launches ADB but what important is to launch ADB and establish the connection.

    When you run ">ADB connect 'IPofYourSmartphone port' " or ADB is run by a soft to get right connection, ADB sends the request which show the panel confirmation on your Smartphone

    This is too valid for USB or Wifi connection. If you use on android a tool like "ADB wireless by Henry" you will get a full guide to get a wifi debugging remote connection.

    call javascript function onchange event of dropdown list

    I don't know why do you need this onmousedown event here, but what you have to do is put your function above actual usage. Look at the snipplet below:

    _x000D_
    _x000D_
    <script type="text/javascript">_x000D_
    function jsFunction(value)_x000D_
    {_x000D_
        alert(value);_x000D_
    }_x000D_
    </script>_x000D_
    _x000D_
    <select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">_x000D_
      <option value='1'>One</option>_x000D_
      <option value='2'>Two</option>_x000D_
      <option value='3'>Three</option>_x000D_
    </select>
    _x000D_
    _x000D_
    _x000D_

    PHP: maximum execution time when importing .SQL data file

    There's a configuration variable within the phpMyAdmin directory that you can find in libraries\config.default.php called $cfg['ExecTimeLimit'] that you can set to whatever maximum execution time you need.

    jQuery - replace all instances of a character in a string

    RegEx is the way to go in most cases.

    In some cases, it may be faster to specify more elements or the specific element to perform the replace on:

    $(document).ready(function () {
        $('.myclass').each(function () {
            $('img').each(function () {
                $(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
            })
        })
    });
    

    This does the replace once on each string, but it does it using a more specific selector.

    Parsing arguments to a Java command line program

    I realize that the question mentions a preference for Commons CLI, but I guess that when this question was asked, there was not much choice in terms of Java command line parsing libraries. But nine years later, in 2020, would you not rather write code like the below?

    import picocli.CommandLine;
    import picocli.CommandLine.Command;
    import picocli.CommandLine.Option;
    import picocli.CommandLine.Parameters;
    import java.io.File;
    import java.util.List;
    import java.util.concurrent.Callable;
    
    @Command(name = "myprogram", mixinStandardHelpOptions = true,
      description = "Does something useful.", version = "1.0")
    public class MyProgram implements Callable<Integer> {
    
        @Option(names = "-r", description = "The r option") String rValue;
        @Option(names = "-S", description = "The S option") String sValue;
        @Option(names = "-A", description = "The A file") File aFile;
        @Option(names = "--test", description = "The test option") boolean test;
        @Parameters(description = "Positional params") List<String> positional;
    
        @Override
        public Integer call() {
            System.out.printf("-r=%s%n", rValue);
            System.out.printf("-S=%s%n", sValue);
            System.out.printf("-A=%s%n", aFile);
            System.out.printf("--test=%s%n", test);
            System.out.printf("positionals=%s%n", positional);
            return 0;
        }
    
        public static void main(String... args) {
            System.exit(new CommandLine(new MyProgram()).execute(args));
        }
    }
    

    Execute by running the command in the question:

    java MyProgram -r opt1 -S opt2 arg1 arg2 arg3 arg4 --test -A opt3
    

    What I like about this code is that it is:

    • compact - no boilerplate
    • declarative - using annotations instead of a builder API
    • strongly typed - annotated fields can be any type, not just String
    • no duplication - option declaration and getting parse result are together in the annotated field
    • clear - the annotations express the intention better than imperative code
    • separation of concerns - the business logic in the call method is free of parsing-related logic
    • convenient - one line of code in main wires up the parser and runs the business logic in the Callable
    • powerful - automatic usage and version help with the built-in --help and --version options
    • user-friendly - usage help message uses colors to contrast important elements like option names from the rest of the usage help to reduce the cognitive load on the user

    The above functionality is only part of what you get when you use the picocli (https://picocli.info) library.

    Now, bear in mind that I am totally, completely, and utterly biased, being the author of picocli. :-) But I do believe that in 2020 we have better alternatives for building a command line apps than Commons CLI.

    How to use a variable inside a regular expression?

    you can try another usage using format grammer suger:

    re_genre = r'{}'.format(your_variable)
    regex_pattern = re.compile(re_genre)  
    

    How can I add a volume to an existing Docker container?

    You can commit your existing container (that is create a new image from container’s changes) and then run it with your new mounts.

    Example:

    $ docker ps  -a
    CONTAINER ID        IMAGE                 COMMAND                  CREATED              STATUS                          PORTS               NAMES
        5a8f89adeead        ubuntu:14.04          "/bin/bash"              About a minute ago   Exited (0) About a minute ago                       agitated_newton
    
    $ docker commit 5a8f89adeead newimagename
    
    $ docker run -ti -v "$PWD/somedir":/somedir newimagename /bin/bash
    

    If it's all OK, stop your old container, and use this new one.

    That´s it :)

    Update elements in a JSONObject

    public static JSONObject updateJson(JSONObject obj, String keyString, String newValue) throws Exception {
                JSONObject json = new JSONObject();
                // get the keys of json object
                Iterator iterator = obj.keys();
                String key = null;
                while (iterator.hasNext()) {
                    key = (String) iterator.next();
                    // if the key is a string, then update the value
                    if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
                        if ((key.equals(keyString))) {
                            // put new value
                            obj.put(key, newValue);
                            return obj;
                        }
                    }
    
                    // if it's jsonobject
                    if (obj.optJSONObject(key) != null) {
                        updateJson(obj.getJSONObject(key), keyString, newValue);
                    }
    
                    // if it's jsonarray
                    if (obj.optJSONArray(key) != null) {
                        JSONArray jArray = obj.getJSONArray(key);
                        for (int i = 0; i < jArray.length(); i++) {
                            updateJson(jArray.getJSONObject(i), keyString, newValue);
                        }
                    }
                }
                return obj;
            }
    

    Set transparent background using ImageMagick and commandline prompt

    Solution

    color=$( convert filename.png -format "%[pixel:p{0,0}]" info:- )
    convert filename.png -alpha off -bordercolor $color -border 1 \
        \( +clone -fuzz 30% -fill none -floodfill +0+0 $color \
           -alpha extract -geometry 200% -blur 0x0.5 \
           -morphology erode square:1 -geometry 50% \) \
        -compose CopyOpacity -composite -shave 1 outputfilename.png
    

    Explanation

    This is rather a bit longer than the simple answers previously given, but it gives much better results: (1) The quality is superior due to antialiased alpha, and (2) only the background is removed as opposed to a single color. ("Background" is defined as approximately the same color as the top left pixel, using a floodfill from the picture edges.)

    Additionally, the alpha channel is also eroded by half a pixel to avoid halos. Of course, ImageMagick's morphological operations don't (yet?) work at the subpixel level, so you can see I am blowing up the alpha channel to 200% before eroding.

    Comparison of results

    Here is a comparison of the simple approach ("-fuzz 2% -transparent white") versus my solution, when run on the ImageMagick logo. I've flattened both transparent images onto a saddle brown background to make the differences apparent (click for originals).

    The simple replacement of white as transparent doesn't always work Antialiased alphachannel and floodfill looks much better

    Notice how the Wizard's beard has disappeared in the simple approach. Compare the edges of the Wizard to see how antialiased alpha helps the figure blend smoothly into the background.

    Of course, I completely admit there are times when you may wish to use the simpler solution. (For example: It's a heck of a lot easier to remember and if you're converting to GIF, you're limited to 1-bit alpha anyhow.)

    mktrans shell script

    Since it's unlikely you'll want to type this command repeatedly, I recommend wrapping it in a script. You can download a BASH shell script from github which performs my suggested solution. It can be run on multiple files in a directory and includes helpful comments in case you want to tweak things.

    bg_removal script

    By the way, ImageMagick actually comes with a script called "bg_removal" which uses floodfill in a similar manner as my solution. However, the results are not great because it still uses 1-bit alpha. Also, the bg_removal script runs slower and is a little bit trickier to use (it requires you to specify two different fuzz values). Here's an example of the output from bg_removal.

    The bg_removal script: has beard, but lacks antialiasing

    Java String array: is there a size of method?

    There is a difference between length of String and array to clarify:

    int a[] = {1, 2, 3, 4};
    String s = "1234";
    
    a.length //gives the length of the array
    
    s.length() //gives the length of the string
    

    Display alert message and redirect after click on accept

    This way it works`

       if ($result_array)
        to_excel($result_array->result_array(), $xls,$campos);
    else {
        echo "<script>alert('There are no fields to generate a report');</script>";
        echo "<script>redirect('admin/ahm/panel'); </script>";
    }`
    

    Docker: Copying files from Docker container to host

    If you don't have a running container, just an image, and assuming you want to copy just a text file, you could do something like this:

    docker run the-image cat path/to/container/file.txt > path/to/host/file.txt
    

    Unexpected character encountered while parsing value

    I had a similar error and thought I'd answer in case anyone was having something similar. I was looping over a directory of json files and deserializing them but was getting this same error.

    The problem was that it was trying to grab hidden files as well. Make sure the file you're passing in is a .json file. I'm guessing it'll handle text as well. Hope this helps.

    How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

    If you want to filter rows by a certain number of columns with null values, you may use this:

    df.iloc[df[(df.isnull().sum(axis=1) >= qty_of_nuls)].index]
    

    So, here is the example:

    Your dataframe:

    >>> df = pd.DataFrame([range(4), [0, np.NaN, 0, np.NaN], [0, 0, np.NaN, 0], range(4), [np.NaN, 0, np.NaN, np.NaN]])
    >>> df
         0    1    2    3
    0  0.0  1.0  2.0  3.0
    1  0.0  NaN  0.0  NaN
    2  0.0  0.0  NaN  0.0
    3  0.0  1.0  2.0  3.0
    4  NaN  0.0  NaN  NaN
    

    If you want to select the rows that have two or more columns with null value, you run the following:

    >>> qty_of_nuls = 2
    >>> df.iloc[df[(df.isnull().sum(axis=1) >=qty_of_nuls)].index]
         0    1    2   3
    1  0.0  NaN  0.0 NaN
    4  NaN  0.0  NaN NaN
    

    Getting attribute using XPath

    How could I get the value of lang (where lang=eng in book title), for the first element?

    Use:

    /*/book[1]/title/@lang
    

    This means:

    Select the lang attribute of the title element that is a child of the first book child of the top element of the XML document.

    To get just the string value of this attribute use the standard XPath function string():

    string(/*/book[1]/title/@lang)
    

    Java: Static Class?

    Just to swim upstream, static members and classes do not participate in OO and are therefore evil. No, not evil, but seriously, I would recommend a regular class with a singleton pattern for access. This way if you need to override behavior in any cases down the road, it isn't a major retooling. OO is your friend :-)

    My $.02

    Ruby - test for array

    Try:

    def is_array(a)
        a.class == Array
    end
    

    EDIT: The other answer is much better than mine.

    MySQL: Large VARCHAR vs. TEXT?

    Can you predict how long the user input would be?

    VARCHAR(X)

    Max Length: variable, up to 65,535 bytes (64KB)
    Case: user name, email, country, subject, password


    TEXT

    Max Length: 65,535 bytes (64KB)
    Case: messages, emails, comments, formatted text, html, code, images, links


    MEDIUMTEXT

    Max Length: 16,777,215 bytes (16MB)
    Case: large json bodies, short to medium length books, csv strings


    LONGTEXT

    Max Length: 4,294,967,29 bytes (4GB)
    Case: textbooks, programs, years of logs files, harry potter and the goblet of fire, scientific research logging

    There's more information on this question.

    Make Error 127 when running trying to compile code

    Error 127 means one of two things:

    1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
    2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

    if the problem is (2), then you can solve it in a few diff ways:

    1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
    2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
    3. build your own cross-compiler using something like crosstool-ng.
    4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

    How can I create a border around an Android LinearLayout?

    Don't want to create a drawable resource?

      <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
        android:minHeight="128dp">
    
        <FrameLayout
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_margin="1dp"
          android:background="@android:color/white">
    
          <TextView ... />
        </FrameLayout>
      </FrameLayout>
    

    Get URL query string parameters

    Programming Language: PHP

    // Inintialize URL to the variable 
    $url = 'https://www.youtube.com/watch?v=qnMxsGeDz90'; 
    
    // Use parse_url() function to parse the URL 
    // and return an associative array which 
    // contains its various components 
    $url_components = parse_url($url); 
    
    // Use parse_str() function to parse the 
    // string passed via URL 
    parse_str($url_components['query'], $params); 
    
    // Display result 
    echo 'v parameter value is '.$params['v'];
    

    This worked for me. I hope, it will also help you :)

    bash: mkvirtualenv: command not found

    On Windows 7 and Git Bash this helps me:

    1. Create a ~/.bashrc file (under your user home folder)
    2. Add line export WORKON_HOME=$HOME/.virtualenvs (you must create this folder if it doesn't exist)
    3. Add line source "C:\Program Files (x86)\Python36-32\Scripts\virtualenvwrapper.sh" (change path for your virtualenvwrapper.sh)

    Restart your git bash and mkvirtualenv command now will work nicely.

    How to remove files and directories quickly via terminal (bash shell)

    So I was looking all over for a way to remove all files in a directory except for some directories, and files, I wanted to keep around. After much searching I devised a way to do it using find.

    find -E . -regex './(dir1|dir2|dir3)' -and -type d -prune -o -print -exec rm -rf {} \;
    

    Essentially it uses regex to select the directories to exclude from the results then removes the remaining files. Just wanted to put it out here in case someone else needed it.

    Batch script to delete files

    There's multiple ways of doing things in batch, so if escaping with a double percent %% isn't working for you, then you could try something like this:

    set olddir=%CD%
    cd /d "path of folder"
    del "file name/ or *.txt etc..."
    cd /d "%olddir%"
    

    How this works:

    set olddir=%CD% sets the variable "olddir" or any other variable name you like to the directory your batch file was launched from.

    cd /d "path of folder" changes the current directory the batch will be looking at. keep the quotations and change path of folder to which ever path you aiming for.

    del "file name/ or *.txt etc..." will delete the file in the current directory your batch is looking at, just don't add a directory path before the file name and just have the full file name or, to delete multiple files with the same extension with *.txt or whatever extension you need.

    cd /d "%olddir%" takes the variable saved with your old path and goes back to the directory you started the batch with, its not important if you don't want the batch going back to its previous directory path, and like stated before the variable name can be changed to whatever you wish by changing the set olddir=%CD% line.

    How to remove all namespaces from XML with C#?

    I know this question is supposedly solved, but I wasn't totally happy with the way it was implemented. I found another source over here on the MSDN blogs that has an overridden XmlTextWriter class that strips out the namespaces. I tweaked it a bit to get some other things I wanted in such as pretty formatting and preserving the root element. Here is what I have in my project at the moment.

    http://blogs.msdn.com/b/kaevans/archive/2004/08/02/206432.aspx

    Class

    /// <summary>
    /// Modified XML writer that writes (almost) no namespaces out with pretty formatting
    /// </summary>
    /// <seealso cref="http://blogs.msdn.com/b/kaevans/archive/2004/08/02/206432.aspx"/>
    public class XmlNoNamespaceWriter : XmlTextWriter
    {
        private bool _SkipAttribute = false;
        private int _EncounteredNamespaceCount = 0;
    
        public XmlNoNamespaceWriter(TextWriter writer)
            : base(writer)
        {
            this.Formatting = System.Xml.Formatting.Indented;
        }
    
        public override void WriteStartElement(string prefix, string localName, string ns)
        {
            base.WriteStartElement(null, localName, null);
        }
    
        public override void WriteStartAttribute(string prefix, string localName, string ns)
        {
            //If the prefix or localname are "xmlns", don't write it.
            //HOWEVER... if the 1st element (root?) has a namespace we will write it.
            if ((prefix.CompareTo("xmlns") == 0
                    || localName.CompareTo("xmlns") == 0)
                && _EncounteredNamespaceCount++ > 0)
            {
                _SkipAttribute = true;
            }
            else
            {
                base.WriteStartAttribute(null, localName, null);
            }
        }
    
        public override void WriteString(string text)
        {
            //If we are writing an attribute, the text for the xmlns
            //or xmlns:prefix declaration would occur here.  Skip
            //it if this is the case.
            if (!_SkipAttribute)
            {
                base.WriteString(text);
            }
        }
    
        public override void WriteEndAttribute()
        {
            //If we skipped the WriteStartAttribute call, we have to
            //skip the WriteEndAttribute call as well or else the XmlWriter
            //will have an invalid state.
            if (!_SkipAttribute)
            {
                base.WriteEndAttribute();
            }
            //reset the boolean for the next attribute.
            _SkipAttribute = false;
        }
    
        public override void WriteQualifiedName(string localName, string ns)
        {
            //Always write the qualified name using only the
            //localname.
            base.WriteQualifiedName(localName, null);
        }
    }
    

    Usage

    //Save the updated document using our modified (almost) no-namespace XML writer
    using(StreamWriter sw = new StreamWriter(this.XmlDocumentPath))
    using(XmlNoNamespaceWriter xw = new XmlNoNamespaceWriter(sw))
    {
        //This variable is of type `XmlDocument`
        this.XmlDocumentRoot.Save(xw);
    }
    

    How to get label text value form a html page?

    Use innerText/textContent:

      var el = document.getElementById('*spaM4');
      console.log(el.innerText || el.textContent);
    

    Fiddle: http://jsfiddle.net/NeTgC/2/

    How to return multiple rows from the stored procedure? (Oracle PL/SQL)

    If you want to use it in plain SQL, I would let the store procedure fill a table or temp table with the resulting rows (or go for @Tony Andrews approach).
    If you want to use @Thilo's solution, you have to loop the cursor using PL/SQL. Here an example: (I used a procedure instead of a function, like @Thilo did)

    create or replace procedure myprocedure(retval in out sys_refcursor) is
    begin
      open retval for
        select TABLE_NAME from user_tables;
    end myprocedure;
    
     declare 
       myrefcur sys_refcursor;
       tablename user_tables.TABLE_NAME%type;
     begin
       myprocedure(myrefcur);
       loop
         fetch myrefcur into tablename;
         exit when myrefcur%notfound;
         dbms_output.put_line(tablename);
       end loop;
       close myrefcur;
     end;
    

    How to check if a file is empty in Bash?

    To check if file is empty or has only white spaces, you can use grep:

    if [[ -z $(grep '[^[:space:]]' $filename) ]] ; then
      echo "Empty file" 
      ...
    fi
    

    How to copy a file to multiple directories using the gnu cp command

    Not using cp per se, but...

    This came up for me in the context of copying lots of Gopro footage off of a (slow) SD card to three (slow) USB drives. I wanted to read the data only once, because it took forever. And I wanted it recursive.

    $ tar cf - src | tee >( cd dest1 ; tar xf - ) >( cd dest2 ; tar xf - ) | ( cd dest3 ; tar xf - )
    

    (And you can add more of those >() sections if you want more outputs.)

    I haven't benchmarked that, but it's definitely a lot faster than cp-in-a-loop (or a bunch of parallel cp invocations).

    The type or namespace name could not be found

    See this question.

    Turns out this was a client profiling issue.

    PrjForm was set to ".Net Framework 4 Client Profile" I changed it to ".Net Framework 4", and now I have a successful build.

    Thanks everyone! I guess it figures that after all that time spent searching online, I find the solution minutes after posting, I guess the trick is knowing the right question to ask..

    How to prevent colliders from passing through each other?

    Collision with fast-moving objects is always a problem. A good way to ensure that you detect all collision is to use Raycasting instead of relying on the physics simulation. This works well for bullets or small objects, but will not produce good results for large objects. http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html

    Pseudo-codeish (I don't have code-completion here and a poor memory):

    void FixedUpdate()
    {
        Vector3 direction = new Vector3(transform.position - lastPosition);
        Ray ray = new Ray(lastPosition, direction);
        RaycastHit hit;
        if (Physics.Raycast(ray, hit, direction.magnitude))
        {
            // Do something if hit
        }
    
        this.lastPosition = transform.position;
    }
    

    Form Google Maps URL that searches for a specific places near specific coordinates

    additional info:

    http://maps.google.com/maps?q=loc: put in latitude and longitude after, example:

    http://maps.google.com/maps?q=loc:51.03841,-114.01679

    this will show pointer on map, but will suppress geocoding of the address, best for a location without an address, or for a location where google maps shows the incorrect address.

    Get Windows version in a batch file

    It's much easier (and faster) to get this information by only parsing the output of ver:

    @echo off
    setlocal
    for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
    if "%version%" == "10.0" echo Windows 10
    if "%version%" == "6.3" echo Windows 8.1
    if "%version%" == "6.2" echo Windows 8.
    if "%version%" == "6.1" echo Windows 7.
    if "%version%" == "6.0" echo Windows Vista.
    rem etc etc
    endlocal
    

    This table on MSDN documents which version number corresponds to which Windows product version (this is where you get the 6.1 means Windows 7 information from).

    The only drawback of this technique is that it cannot distinguish between the equivalent server and consumer versions of Windows.

    Non-numeric Argument to Binary Operator Error in R

    Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

    - is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

    A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

    R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

    > 1 + 1
    [1] 2
    > 1 + 'one'
    Error in 1 + "one" : non-numeric argument to binary operator
    

    When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

    EDIT:

    Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

    > Day <- Transaction(1, 2)["b"]
    > class(Day)
    [1] "list"
    > Day + 1
    Error in Day + 1 : non-numeric argument to binary operator
    
    > Day2 <- Transaction(1, 2)[["b"]]
    > class(Day2)
    [1] "numeric"
    > Day2 + 1
    [1] 3
    

    Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

    How can I combine two commits into one commit?

    You want to git rebase -i to perform an interactive rebase.

    If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.

    Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f and anybody sharing your code will have to jump through some hoops to pull your changes.

    Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.

    Postgres password authentication fails

    Assuming, that you have root access on the box you can do:

    sudo -u postgres psql
    

    If that fails with a database "postgres" does not exists this block.

    sudo -u postgres psql template1
    

    Then sudo nano /etc/postgresql/11/main/pg_hba.conf file

    local   all         postgres                          ident
    

    For newer versions of PostgreSQL ident actually might be peer.

    Inside the psql shell you can give the DB user postgres a password:

    ALTER USER postgres PASSWORD 'newPassword';
    

    Bootstrap: Collapse other sections when one is expanded

    The Method Works Properly For me:

    var lanopt = $(".language-option");
    
    lanopt.on("show.bs.collapse",".collapse", function(){
       lanopt.find(".collapse.in").collapse("hide");
    });
    

    Making the iPhone vibrate

    A simple way to do so is with Audio Services:

    #import <AudioToolbox/AudioToolbox.h> 
    ...    
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    

    Capture Video of Android's Screen

    I have not used the app, but I've seen Rec. referenced as a way to do this, but you need root the phone.

    Compare a string using sh shell

    -eq is the shell comparison operator for comparing integers. For comparing strings you need to use =.

    Taking inputs with BufferedReader in Java

    BufferedReader#read reads single character[0 to 65535 (0x00-0xffff)] from the stream, so it is not possible to read single integer from stream.

                String s= inp.readLine();
                int[] m= new int[2];
                String[] s1 = inp.readLine().split(" ");
                m[0]=Integer.parseInt(s1[0]);
                m[1]=Integer.parseInt(s1[1]);
    
                // Checking whether I am taking the inputs correctly
                System.out.println(s);
                System.out.println(m[0]);
                System.out.println(m[1]);
    

    You can check also Scanner vs. BufferedReader.

    Calculating time difference in Milliseconds

    In such a small cases where difference is less than 0 milliseconds you can get difference in nano seconds as well.

    System.nanoTime()
    

    How to change port number for apache in WAMP

    Just go to httpd.conf file, for ex. under WAMP environment its situated at:

    C:\wamp\bin\apache\apache2.2.22\conf\httpd.conf
    

    go to line no. 46 and edit Listen 80 to your requirement for ex.

    Listen 8383
    

    newer versions of WAMP uses these 2 lines:

    Listen 0.0.0.0:8383  
    Listen [::0]:8383
    

    Next go to line no. 171 and edit ServerName localhost:80 to your requirement for ex.

    ServerName localhost:8383
    

    Restart Apache and its done !!

    Now, you can access with your URL:

    http://localhost:8383 or http://192.168.1.1:8383
    

    Hope it helps to people looking for solution here.

    When to use extern in C++

    It's all about the linkage.

    The previous answers provided good explainations about extern.

    But I want to add an important point.

    You ask about extern in C++ not in C and I don't know why there is no answer mentioning about the case when extern comes with const in C++.

    In C++, a const variable has internal linkage by default (not like C).

    So this scenario will lead to linking error:

    Source 1 :

    const int global = 255; //wrong way to make a definition of global const variable in C++
    

    Source 2 :

    extern const int global; //declaration
    

    It need to be like this:

    Source 1 :

    extern const int global = 255; //a definition of global const variable in C++
    

    Source 2 :

    extern const int global; //declaration
    

    How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

    I had the exact same issue on my branch(lets call it branch B) and I followed three simple steps to get make it work

    1. Switched to the master branch (git checkout master)
    2. Did a pull on the master (git pull)
    3. Created new branch (git branch C) - note here that we are now branching from master
    4. Now when you are on branch C, merge with branch B (git merge B)
    5. Now do a push (git push origin C) - works :)

    Now you can delete branch B and then rename branch C to branch B.

    Hope this helps.

    How do I bind a WPF DataGrid to a variable number of columns?

    I've continued my research and have not found any reasonable way to do this. The Columns property on the DataGrid isn't something I can bind against, in fact it's read only.

    Bryan suggested something might be done with AutoGenerateColumns so I had a look. It uses simple .Net reflection to look at the properties of the objects in ItemsSource and generates a column for each one. Perhaps I could generate a type on the fly with a property for each column but this is getting way off track.

    Since this problem is so easily sovled in code I will stick with a simple extension method I call whenever the data context is updated with new columns:

    public static void GenerateColumns(this DataGrid dataGrid, IEnumerable<ColumnSchema> columns)
    {
        dataGrid.Columns.Clear();
    
        int index = 0;
        foreach (var column in columns)
        {
            dataGrid.Columns.Add(new DataGridTextColumn
            {
                Header = column.Name,
                Binding = new Binding(string.Format("[{0}]", index++))
            });
        }
    }
    
    // E.g. myGrid.GenerateColumns(schema);
    

    How can I setup & run PhantomJS on Ubuntu?

    For PhantomJS version above 1.5, consider this (verbatim copy of the build instructions on the phantom website):

    For Ubuntu Linux (tested on a barebone install of Ubuntu 10.04 Lucid Lynx and Ubuntu 11.04 Natty Narwhal):

    sudo apt-get install build-essential chrpath git-core libssl-dev libfontconfig1-dev
    git clone git://github.com/ariya/phantomjs.git
    cd phantomjs
    git checkout 1.7
    ./build.sh
    

    How to scan multiple paths using the @ComponentScan annotation?

    There is another type-safe alternative to specifying a base-package location as a String. See the API here, but I've also illustrated below:

    @ComponentScan(basePackageClasses = {ExampleController.class, ExampleModel.class, ExmapleView.class})
    

    Using the basePackageClasses specifier with your class references will tell Spring to scan those packages (just like the mentioned alternatives), but this method is both type-safe and adds IDE support for future refactoring -- a huge plus in my book.

    Reading from the API, Spring suggests creating a no-op marker class or interface in each package you wish to scan that serves no other purpose than to be used as a reference for/by this attribute.

    IMO, I don't like the marker-classes (but then again, they are pretty much just like the package-info classes) but the type safety, IDE support, and drastically reducing the number of base packages needed to include for this scan is, with out a doubt, a far better option.

    Is it possible to use "return" in stored procedure?

    It is possible.

    When you use Return inside a procedure, the control is transferred to the calling program which calls the procedure. It is like an exit in loops.

    It won't return any value.

    How can I debug git/git-shell related problems?

    For even more verbose output use following:

    GIT_CURL_VERBOSE=1 GIT_TRACE=1 git pull origin master

    Do I cast the result of malloc?

    TL;DR

    int *sieve = (int *) malloc(sizeof(int) * length);
    

    has two problems. The cast and that you're using the type instead of variable as argument for sizeof. Instead, do like this:

    int *sieve = malloc(sizeof *sieve * length);
    

    Long version

    No; you don't cast the result, since:

    • It is unnecessary, as void * is automatically and safely promoted to any other pointer type in this case.
    • It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).
    • It makes you repeat yourself, which is generally bad.
    • It can hide an error if you forgot to include <stdlib.h>. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address. Note: as of C99 implicit functions are gone from C, and this point is no longer relevant since there's no automatic assumption that undeclared functions return int.

    As a clarification, note that I said "you don't cast", not "you don't need to cast". In my opinion, it's a failure to include the cast, even if you got it right. There are simply no benefits to doing it, but a bunch of potential risks, and including the cast indicates that you don't know about the risks.

    Also note, as commentators point out, that the above talks about straight C, not C++. I very firmly believe in C and C++ as separate languages.

    To add further, your code needlessly repeats the type information (int) which can cause errors. It's better to de-reference the pointer being used to store the return value, to "lock" the two together:

    int *sieve = malloc(length * sizeof *sieve);
    

    This also moves the length to the front for increased visibility, and drops the redundant parentheses with sizeof; they are only needed when the argument is a type name. Many people seem to not know (or ignore) this, which makes their code more verbose. Remember: sizeof is not a function! :)


    While moving length to the front may increase visibility in some rare cases, one should also pay attention that in the general case, it should be better to write the expression as:

    int *sieve = malloc(sizeof *sieve * length);
    

    Since keeping the sizeof first, in this case, ensures multiplication is done with at least size_t math.

    Compare: malloc(sizeof *sieve * length * width) vs. malloc(length * width * sizeof *sieve) the second may overflow the length * width when width and length are smaller types than size_t.

    vba listbox multicolumn add

    Simplified example (with counter):

    With Me.lstbox
        .ColumnCount = 2
        .ColumnWidths = "60;60"
        .AddItem
        .List(i, 0) = Company_ID
        .List(i, 1) = Company_name 
        i = i + 1
    
    end with
    

    Make sure to start the counter with 0, not 1 to fill up a listbox.

    Counting array elements in Python

    If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:

    import numpy as np
    a = np.arange(10).reshape(2, 5)
    print len(a) == 2
    

    This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.

    import numpy as np
    len(a) == np.shape(a)[0]
    

    To get the number of elements in a multi-dimensional array of arbitrary shape:

    import numpy as np
    size = 1
    for dim in np.shape(a): size *= dim
    

    How do I share variables between different .c files?

    The 2nd file needs to know about the existance of your variable. To do this you declare the variable again but use the keyword extern in front of it. This tells the compiler that the variable is available but declared somewhere else, thus prevent instanciating it (again, which would cause clashes when linking). While you can put the extern declaration in the C file itself it's common style to have an accompanying header (i.e. .h) file for each .c file that provides functions or variables to others which hold the extern declaration. This way you avoid copying the extern declaration, especially if it's used in multiple other files. The same applies for functions, though you don't need the keyword extern for them.

    That way you would have at least three files: the source file that declares the variable, it's acompanying header that does the extern declaration and the second source file that #includes the header to gain access to the exported variable (or any other symbol exported in the header). Of course you need all source files (or the appropriate object files) when trying to link something like that, as the linker needs to resolve the symbol which is only possible if it actually exists in the files linked.

    scroll up and down a div on button click using jquery

    Scrolling div on click of button.

    Html Code:-

     <div id="textBody" style="height:200px; width:600px; overflow:auto;">
        <!------Your content---->
     </div>
    

    JQuery code for scrolling div:-

    $(function() {
       $( "#upBtn" ).click(function(){
          $('#textBody').scrollTop($('#textBody').scrollTop()-20);
     }); 
    
     $( "#downBtn" ).click(function(){
         $('#textBody').scrollTop($('#textBody').scrollTop()+20);;
     }); 
    
    });
    

    Iterator invalidation rules

    C++11 (Source: Iterator Invalidation Rules (C++0x))


    Insertion

    Sequence containers

    • vector: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.3.6.5/1]
    • deque: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.3.3.4/1]
    • list: all iterators and references unaffected [23.3.5.4/1]
    • forward_list: all iterators and references unaffected (applies to insert_after) [23.3.4.5/1]
    • array: (n/a)

    Associative containers

    • [multi]{set,map}: all iterators and references unaffected [23.2.4/9]

    Unsorted associative containers

    • unordered_[multi]{set,map}: all iterators invalidated when rehashing occurs, but references unaffected [23.2.5/8]. Rehashing does not occur if the insertion does not cause the container's size to exceed z * B where z is the maximum load factor and B the current number of buckets. [23.2.5/14]

    Container adaptors

    • stack: inherited from underlying container
    • queue: inherited from underlying container
    • priority_queue: inherited from underlying container

    Erasure

    Sequence containers

    • vector: every iterator and reference at or after the point of erase is invalidated [23.3.6.5/3]
    • deque: erasing the last element invalidates only iterators and references to the erased elements and the past-the-end iterator; erasing the first element invalidates only iterators and references to the erased elements; erasing any other elements invalidates all iterators and references (including the past-the-end iterator) [23.3.3.4/4]
    • list: only the iterators and references to the erased element is invalidated [23.3.5.4/3]
    • forward_list: only the iterators and references to the erased element is invalidated (applies to erase_after) [23.3.4.5/1]
    • array: (n/a)

    Associative containers

    • [multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.4/9]

    Unordered associative containers

    • unordered_[multi]{set,map}: only iterators and references to the erased elements are invalidated [23.2.5/13]

    Container adaptors

    • stack: inherited from underlying container
    • queue: inherited from underlying container
    • priority_queue: inherited from underlying container

    Resizing

    • vector: as per insert/erase [23.3.6.5/12]
    • deque: as per insert/erase [23.3.3.3/3]
    • list: as per insert/erase [23.3.5.3/1]
    • forward_list: as per insert/erase [23.3.4.5/25]
    • array: (n/a)

    Note 1

    Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.2.1/11]

    Note 2

    no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [23.2.1/10]

    Note 3

    Other than the above caveat regarding swap(), it's not clear whether "end" iterators are subject to the above listed per-container rules; you should assume, anyway, that they are.

    Note 4

    vector and all unordered associative containers support reserve(n) which guarantees that no automatic resizing will occur at least until the size of the container grows to n. Caution should be taken with unordered associative containers because a future proposal will allow the specification of a minimum load factor, which would allow rehashing to occur on insert after enough erase operations reduce the container size below the minimum; the guarantee should be considered potentially void after an erase.

    Sorting object property by values

    Sort values without multiple for-loops (to sort by the keys change index in the sort callback to "0")

    _x000D_
    _x000D_
    const list = {_x000D_
        "you": 100, _x000D_
        "me": 75, _x000D_
        "foo": 116, _x000D_
        "bar": 15_x000D_
      };_x000D_
    _x000D_
    let sorted = Object.fromEntries(_x000D_
                    Object.entries(list).sort( (a,b) => a[1] - b[1] )    _x000D_
                 ) _x000D_
    console.log('Sorted object: ', sorted) 
    _x000D_
    _x000D_
    _x000D_

    How to get date, month, year in jQuery UI datepicker?

    You can use method getDate():

    $('#calendar').datepicker({
        dateFormat: 'yy-m-d',
        inline: true,
        onSelect: function(dateText, inst) { 
            var date = $(this).datepicker('getDate'),
                day  = date.getDate(),  
                month = date.getMonth() + 1,              
                year =  date.getFullYear();
            alert(day + '-' + month + '-' + year);
        }
    });
    

    FIDDLE

    Error when deploying an artifact in Nexus

    • in the parent pom application==> Version put the tag as follows: x.x.x-SNAPSHOT

    example :0.0.1-SNAPSHOT

    • "-SNAPSHOT" : is very important

    Import an existing git project into GitLab?

    Here are the steps provided by the Gitlab:

    cd existing_repo
    git remote rename origin old-origin
    git remote add origin https://gitlab.example.com/rmishra/demoapp.git
    git push -u origin --all
    git push -u origin --tags
    

    What does print(... sep='', '\t' ) mean?

    sep='' in the context of a function call sets the named argument sep to an empty string. See the print() function; sep is the separator used between multiple values when printing. The default is a space (sep=' '), this function call makes sure that there is no space between Property tax: $ and the formatted tax floating point value.

    Compare the output of the following three print() calls to see the difference

    >>> print('foo', 'bar')
    foo bar
    >>> print('foo', 'bar', sep='')
    foobar
    >>> print('foo', 'bar', sep=' -> ')
    foo -> bar
    

    All that changed is the sep argument value.

    \t in a string literal is an escape sequence for tab character, horizontal whitespace, ASCII codepoint 9.

    \t is easier to read and type than the actual tab character. See the table of recognized escape sequences for string literals.

    Using a space or a \t tab as a print separator shows the difference:

    >>> print('eggs', 'ham')
    eggs ham
    >>> print('eggs', 'ham', sep='\t')
    eggs    ham
    

    How to change the locale in chrome browser

    Use ModHeader Chrome extension.

    enter image description here

    Or you can try more complex value like Accept-Language: en-US,en;q=0.9,ru;q=0.8,th;q=0.7

    How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

    As of 27 February 2019, there are CSS fonts for the new Material Icon themes.

    However, you have to create CSS classes to use the fonts.

    The font families are as follows:

    • Material Icons Outlined - Outlined icons
    • Material Icons Two Tone - Two-tone icons
    • Material Icons Round - Rounded icons
    • Material Icons Sharp - Sharp icons

    See the code sample below for an example:

    _x000D_
    _x000D_
    body {_x000D_
      font-family: Roboto, sans-serif;_x000D_
    }_x000D_
    _x000D_
    .material-icons-outlined,_x000D_
    .material-icons.material-icons--outlined,_x000D_
    .material-icons-two-tone,_x000D_
    .material-icons.material-icons--two-tone,_x000D_
    .material-icons-round,_x000D_
    .material-icons.material-icons--round,_x000D_
    .material-icons-sharp,_x000D_
    .material-icons.material-icons--sharp {_x000D_
      font-weight: normal;_x000D_
      font-style: normal;_x000D_
      font-size: 24px;_x000D_
      line-height: 1;_x000D_
      letter-spacing: normal;_x000D_
      text-transform: none;_x000D_
      display: inline-block;_x000D_
      white-space: nowrap;_x000D_
      word-wrap: normal;_x000D_
      direction: ltr;_x000D_
      -webkit-font-feature-settings: 'liga';_x000D_
      -webkit-font-smoothing: antialiased;_x000D_
    }_x000D_
    _x000D_
    .material-icons-outlined,_x000D_
    .material-icons.material-icons--outlined {_x000D_
      font-family: 'Material Icons Outlined';_x000D_
    }_x000D_
    _x000D_
    .material-icons-two-tone,_x000D_
    .material-icons.material-icons--two-tone {_x000D_
      font-family: 'Material Icons Two Tone';_x000D_
    }_x000D_
    _x000D_
    .material-icons-round,_x000D_
    .material-icons.material-icons--round {_x000D_
      font-family: 'Material Icons Round';_x000D_
    }_x000D_
    _x000D_
    .material-icons-sharp,_x000D_
    .material-icons.material-icons--sharp {_x000D_
      font-family: 'Material Icons Sharp';_x000D_
    }
    _x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    _x000D_
    <head>_x000D_
      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500|Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp">_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
      <section id="original">_x000D_
        <h2>Baseline</h2>_x000D_
        <i class="material-icons">home</i>_x000D_
        <i class="material-icons">assignment</i>_x000D_
      </section>_x000D_
      <section id="outlined">_x000D_
        <h2>Outlined</h2>_x000D_
        <i class="material-icons-outlined">home</i>_x000D_
        <i class="material-icons material-icons--outlined">assignment</i>_x000D_
      </section>_x000D_
      <section id="two-tone">_x000D_
        <h2>Two tone</h2>_x000D_
        <i class="material-icons-two-tone">home</i>_x000D_
        <i class="material-icons material-icons--two-tone">assignment</i>_x000D_
      </section>_x000D_
      <section id="rounded">_x000D_
        <h2>Rounded</h2>_x000D_
        <i class="material-icons-round">home</i>_x000D_
        <i class="material-icons material-icons--round">assignment</i>_x000D_
      </section>_x000D_
      <section id="sharp">_x000D_
        <h2>Sharp</h2>_x000D_
        <i class="material-icons-sharp">home</i>_x000D_
        <i class="material-icons material-icons--sharp">assignment</i>_x000D_
      </section>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Or view it on Codepen


    EDIT: As of 10 March 2019, it appears that there are now classes for the new font icons:

    _x000D_
    _x000D_
    body {_x000D_
      font-family: Roboto, sans-serif;_x000D_
    }
    _x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    _x000D_
    <head>_x000D_
      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500|Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp">_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
      <section id="original">_x000D_
        <h2>Baseline</h2>_x000D_
        <i class="material-icons">home</i>_x000D_
        <i class="material-icons">assignment</i>_x000D_
      </section>_x000D_
      <section id="outlined">_x000D_
        <h2>Outlined</h2>_x000D_
        <i class="material-icons-outlined">home</i>_x000D_
        <i class="material-icons-outlined">assignment</i>_x000D_
      </section>_x000D_
      <section id="two-tone">_x000D_
        <h2>Two tone</h2>_x000D_
        <i class="material-icons-two-tone">home</i>_x000D_
        <i class="material-icons-two-tone">assignment</i>_x000D_
      </section>_x000D_
      <section id="rounded">_x000D_
        <h2>Rounded</h2>_x000D_
        <i class="material-icons-round">home</i>_x000D_
        <i class="material-icons-round">assignment</i>_x000D_
      </section>_x000D_
      <section id="sharp">_x000D_
        <h2>Sharp</h2>_x000D_
        <i class="material-icons-sharp">home</i>_x000D_
        <i class="material-icons-sharp">assignment</i>_x000D_
      </section>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    EDIT #2: Here's a workaround to tint two-tone icons by using CSS image filters (code adapted from this comment):

    _x000D_
    _x000D_
    body {_x000D_
      font-family: Roboto, sans-serif;_x000D_
    }_x000D_
    _x000D_
    .material-icons-two-tone {_x000D_
      filter: invert(0.5) sepia(1) saturate(10) hue-rotate(180deg);_x000D_
      font-size: 48px;_x000D_
    }_x000D_
    _x000D_
    .material-icons,_x000D_
    .material-icons-outlined,_x000D_
    .material-icons-round,_x000D_
    .material-icons-sharp {_x000D_
      color: #0099ff;_x000D_
      font-size: 48px;_x000D_
    }
    _x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    _x000D_
    <head>_x000D_
      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500|Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp">_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
      <section id="original">_x000D_
        <h2>Baseline</h2>_x000D_
        <i class="material-icons">home</i>_x000D_
        <i class="material-icons">assignment</i>_x000D_
      </section>_x000D_
      <section id="outlined">_x000D_
        <h2>Outlined</h2>_x000D_
        <i class="material-icons-outlined">home</i>_x000D_
        <i class="material-icons-outlined">assignment</i>_x000D_
      </section>_x000D_
      <section id="two-tone">_x000D_
        <h2>Two tone</h2>_x000D_
        <i class="material-icons-two-tone">home</i>_x000D_
        <i class="material-icons-two-tone">assignment</i>_x000D_
      </section>_x000D_
      <section id="rounded">_x000D_
        <h2>Rounded</h2>_x000D_
        <i class="material-icons-round">home</i>_x000D_
        <i class="material-icons-round">assignment</i>_x000D_
      </section>_x000D_
      <section id="sharp">_x000D_
        <h2>Sharp</h2>_x000D_
        <i class="material-icons-sharp">home</i>_x000D_
        <i class="material-icons-sharp">assignment</i>_x000D_
      </section>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Or view it on Codepen

    How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

    For me, something different worked, that I found in on this answer from a similar question. Probably won't help OP, but maybe someone like me that had a similar problem.

    You should indeed use rvm, but as no one explained to you how to do this without rvm, here you go:

    sudo gem install tzinfo builder memcache-client rack rack-test rack-mount \
      abstract erubis activesupport mime-types mail text-hyphen text-format   \
      thor i18n rake bundler arel railties rails --prerelease --force
    

    AVD Manager - No system image installed for this target

    you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

    if not installed ARM EABI v7a System Image, you should install all.

    Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

    you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java

    Java BigDecimal: Round to the nearest whole value

    I don't think you can round it like that in a single command. Try

        ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
        list.add(new BigDecimal("100.12"));
        list.add(new BigDecimal("100.44"));
        list.add(new BigDecimal("100.50"));
        list.add(new BigDecimal("100.75"));
    
        for (BigDecimal bd : list){
            System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
        }
    
    Output:
    100.12 -> 100.00
    100.44 -> 100.00
    100.50 -> 101.00
    100.75 -> 101.00
    

    I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

    javascript window.location in new tab

    I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open and hoping that the user has their browser set to open new windows in new tabs.

    What is the Swift equivalent of respondsToSelector?

    I use guard let else, so that can do some default stuff if the delegate func is not implemented.

    @objc protocol ViewController2Delegate: NSObjectProtocol {
    
        optional func viewController2(controller: ViewController2, didSomethingWithStringAndReturnVoid string: String)
    
        optional func viewController2(controller: ViewController2, didSomethingWithStringAndReturnString string: String) -> String
    }
    
    class ViewController2: UIViewController {
    
        weak var delegate: ViewController2Delegate?        
    
        @IBAction func onVoidButtonClicked(sender: AnyObject){
    
            if (delegate != nil && delegate!.respondsToSelector(Selector("viewController2:didSomethingWithStringAndReturnVoid:"))) {
                NSLog("ReturnVoid is implemented")
    
                delegate!.viewController2!(self, didSomethingWithStringAndReturnVoid: "dummy")
            }
            else{
                NSLog("ReturnVoid is not implemented")
                // Do something by default
            }
        }
    
        @IBAction func onStringButtonClicked(sender: AnyObject){
    
            guard let result = delegate?.viewController2?(self, didSomethingWithStringAndReturnString: "dummy") else {
                NSLog("ReturnString is not implemented")
                // Do something by default
                return
            }
    
            NSLog("ReturnString is implemented with result: \(result)")
        }
    }
    

    How to push a docker image to a private repository

    There are two options:

    1. Go into the hub, and create the repository first, and mark it as private. Then when you push to that repo, it will be private. This is the most common approach.

    2. log into your docker hub account, and go to your global settings. There is a setting that allows you to set what your default visability is for the repositories that you push. By default it is set to public, but if you change it to private, all of your repositories that you push will be marked as private by default. It is important to note that you will need to have enough private repos available on your account, or else the repo will be locked until you upgrade your plan.

    How do I select between the 1st day of the current month and current day in MySQL?

    select * from <table>
    where <dateValue> between last_day(curdate() - interval 1 month + interval 1 day)
                      and curdate();
    

    Reset ID autoincrement ? phpmyadmin

    You can also do this in phpMyAdmin without writing SQL.

    • Click on a database name in the left column.
    • Click on a table name in the left column.
    • Click the "Operations" tab at the top.
    • Under "Table options" there should be a field for AUTO_INCREMENT (only on tables that have an auto-increment field).
    • Input desired value and click the "Go" button below.

    Note: You'll see that phpMyAdmin is issuing the same SQL that is mentioned in the other answers.

    Server did not recognize the value of HTTP Header SOAPAction

    Just to help someone on this problem, after an afternoon of debug, the problem was that the web service was developed with framework 4.5 and the call from android must be done with SoapEnvelope.VER12 and not with SoapEnvelope.VER11

    How can I exclude one word with grep?

    You can do it using -v (for --invert-match) option of grep as:

    grep -v "unwanted_word" file | grep XXXXXXXX
    

    grep -v "unwanted_word" file will filter the lines that have the unwanted_word and grep XXXXXXXX will list only lines with pattern XXXXXXXX.

    EDIT:

    From your comment it looks like you want to list all lines without the unwanted_word. In that case all you need is:

    grep -v 'unwanted_word' file
    

    How to sort a list/tuple of lists/tuples by the element at a given index?

    @Stephen 's answer is to the point! Here is an example for better visualization,

    Shout out for the Ready Player One fans! =)

    >>> gunters = [('2044-04-05', 'parzival'), ('2044-04-07', 'aech'), ('2044-04-06', 'art3mis')]
    >>> gunters.sort(key=lambda tup: tup[0])
    >>> print gunters
    [('2044-04-05', 'parzival'), ('2044-04-06', 'art3mis'), ('2044-04-07', 'aech')]
    

    key is a function that will be called to transform the collection's items for comparison.. like compareTo method in Java.

    The parameter passed to key must be something that is callable. Here, the use of lambda creates an anonymous function (which is a callable).
    The syntax of lambda is the word lambda followed by a iterable name then a single block of code.

    Below example, we are sorting a list of tuple that holds the info abt time of certain event and actor name.

    We are sorting this list by time of event occurrence - which is the 0th element of a tuple.

    Note - s.sort([cmp[, key[, reverse]]]) sorts the items of s in place

    text-align: right on <select> or <option>

    You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?

    <select dir="rtl">
        <option>Foo</option>    
        <option>bar</option>
        <option>to the right</option>
    </select>
    

    Demo here: http://jsfiddle.net/fparent/YSJU7/

    What does "subject" mean in certificate?

    Subject is the certificate's common name and is a critical property for the certificate in a lot of cases if it's a server certificate and clients are looking for a positive identification.

    As an example on an SSL certificate for a web site the subject would be the domain name of the web site.

    Converting <br /> into a new line for use in a text area

    Try this one

    <?php
        $text = "Hello <br /> Hello again <br> Hello again again <br/> Goodbye <BR>";
        $breaks = array("<br />","<br>","<br/>");  
        $text = str_ireplace($breaks, "\r\n", $text);  
    ?>  
    <textarea><?php echo $text; ?></textarea>
    

    convert php date to mysql format

    There is several options.

    Either convert it to timestamp and use as instructed in other posts with strtotime() or use MySQL’s date parsing option

    What is difference between cacerts and keystore?

    Cacerts are details of trusted signing authorities who can issue certs. This what most of the browsers have due to which certs determined to be authentic. Keystone has your service related certs to authenticate clients.

    Python Matplotlib figure title overlaps axes label when using twiny

    You can use pad for this case:

    ax.set_title("whatever", pad=20)
    

    In git, what is the difference between merge --squash and rebase?

    Both git merge --squash and git rebase --interactive can produce a "squashed" commit.
    But they serve different purposes.

    will produce a squashed commit on the destination branch, without marking any merge relationship.
    (Note: it does not produce a commit right away: you need an additional git commit -m "squash branch")
    This is useful if you want to throw away the source branch completely, going from (schema taken from SO question):

     git checkout stable
    
          X                   stable
         /                   
    a---b---c---d---e---f---g tmp
    

    to:

    git merge --squash tmp
    git commit -m "squash tmp"
    
          X-------------------G stable
         /                   
    a---b---c---d---e---f---g tmp
    

    and then deleting tmp branch.


    Note: git merge has a --commit option, but it cannot be used with --squash. It was never possible to use --commit and --squash together.
    Since Git 2.22.1 (Q3 2019), this incompatibility is made explicit:

    See commit 1d14d0c (24 May 2019) by Vishal Verma (reloadbrain).
    (Merged by Junio C Hamano -- gitster -- in commit 33f2790, 25 Jul 2019)

    merge: refuse --commit with --squash

    Previously, when --squash was supplied, 'option_commit' was silently dropped. This could have been surprising to a user who tried to override the no-commit behavior of squash using --commit explicitly.

    git/git builtin/merge.c#cmd_merge() now includes:

    if (option_commit > 0)
        die(_("You cannot combine --squash with --commit."));
    

    replays some or all of your commits on a new base, allowing you to squash (or more recently "fix up", see this SO question), going directly to:

    git checkout tmp
    git rebase -i stable
    
          stable
          X-------------------G tmp
         /                     
    a---b
    

    If you choose to squash all commits of tmp (but, contrary to merge --squash, you can choose to replay some, and squashing others).

    So the differences are:

    • squash does not touch your source branch (tmp here) and creates a single commit where you want.
    • rebase allows you to go on on the same source branch (still tmp) with:
      • a new base
      • a cleaner history

    MySQL "NOT IN" query

    Be carefull NOT IN is not an alias for <> ANY, but for <> ALL!

    http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html

    SELECT c FROM t1 LEFT JOIN t2 USING (c) WHERE t2.c IS NULL
    

    cant' be replaced by

    SELECT c FROM t1 WHERE c NOT IN (SELECT c FROM t2)
    

    You must use

    SELECT c FROM t1 WHERE c <> ANY (SELECT c FROM t2)
    

    How do I hide the bullets on my list for the sidebar?

    You have a selector ul on line 252 which is setting list-style: square outside none (a square bullet). You'll have to change it to list-style: none or just remove the line.

    If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:

    ul#groups-list.items-list { list-style: none }
    

    Why emulator is very slow in Android Studio?

    Check this list:

    1. install Intel HAXM
    2. just use x86 AVD
    3. use small size screen

    Replacing a character from a certain index

    # Use slicing to extract those parts of the original string to be kept
    s = s[:position] + replacement + s[position+length_of_replaced:]
    
    # Example: replace 'sat' with 'slept'
    text = "The cat sat on the mat"
    text = text[:8] + "slept" + text[11:]
    

    I/P : The cat sat on the mat

    O/P : The cat slept on the mat

    Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

    You can use functions in pyspark.sql.functions: functions like year, month, etc

    refer to here: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame

    from pyspark.sql.functions import *
    
    newdf = elevDF.select(year(elevDF.date).alias('dt_year'), month(elevDF.date).alias('dt_month'), dayofmonth(elevDF.date).alias('dt_day'), dayofyear(elevDF.date).alias('dt_dayofy'), hour(elevDF.date).alias('dt_hour'), minute(elevDF.date).alias('dt_min'), weekofyear(elevDF.date).alias('dt_week_no'), unix_timestamp(elevDF.date).alias('dt_int'))
    
    newdf.show()
    
    
    +-------+--------+------+---------+-------+------+----------+----------+
    |dt_year|dt_month|dt_day|dt_dayofy|dt_hour|dt_min|dt_week_no|    dt_int|
    +-------+--------+------+---------+-------+------+----------+----------+
    |   2015|       9|     6|      249|      0|     0|        36|1441497601|
    |   2015|       9|     6|      249|      0|     0|        36|1441497601|
    |   2015|       9|     6|      249|      0|     0|        36|1441497603|
    |   2015|       9|     6|      249|      0|     1|        36|1441497694|
    |   2015|       9|     6|      249|      0|    20|        36|1441498808|
    |   2015|       9|     6|      249|      0|    20|        36|1441498811|
    |   2015|       9|     6|      249|      0|    20|        36|1441498815|
    

    Set width of dropdown element in HTML select dropdown options

    I find the best way to handle long dropdown boxes is to put it inside a fixed width div container and use width:auto on the select tag. Most browsers will contain the dropdown within the div, but when you click on it, it will expand to display the full option value. It does not work with IE explorer, but there is a fix (like is always needed with IE). Your code would look something like this.

    HTML

    <div class="dropdown_container">
      <select class="my_dropdown" id="my_dropdown">
        <option value="1">LONG OPTION</option>
        <option value="2">short</option>
      </select>
    </div>
    

    CSS

    div.dropdown_container {
        width:10px;
    }
    
    select.my_dropdown {
        width:auto;
    }
    
    /*IE FIX */
    select#my_dropdown {
        width:100%;
    }
    
    select:focus#my_dropdown {
        width:auto\9;
    }
    

    Getting a File's MD5 Checksum in Java

    I recently had to do this for just a dynamic string, MessageDigest can represent the hash in numerous ways. To get the signature of the file like you would get with the md5sum command I had to do something like the this:

    try {
       String s = "TEST STRING";
       MessageDigest md5 = MessageDigest.getInstance("MD5");
       md5.update(s.getBytes(),0,s.length());
       String signature = new BigInteger(1,md5.digest()).toString(16);
       System.out.println("Signature: "+signature);
    
    } catch (final NoSuchAlgorithmException e) {
       e.printStackTrace();
    }
    

    This obviously doesn't answer your question about how to do it specifically for a file, the above answer deals with that quiet nicely. I just spent a lot of time getting the sum to look like most application's display it, and thought you might run into the same trouble.

    How to update and order by using ms sql

    I have to offer this as a better approach - you don't always have the luxury of an identity field:

    UPDATE m
    SET [status]=10
    FROM (
      Select TOP (10) *
      FROM messages
      WHERE [status]=0
      ORDER BY [priority] DESC
    ) m
    

    You can also make the sub-query as complicated as you want - joining multiple tables, etc...

    Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages table. It can be used to update the top N rows from any table, even if that table has no unique key at all.

    Deleting a local branch with Git

    Switch to some other branch and delete Test_Branch, as follows:

    $ git checkout master
    $ git branch -d Test_Branch
    

    If above command gives you error - The branch 'Test_Branch' is not fully merged. If you are sure you want to delete it and still you want to delete it, then you can force delete it using -D instead of -d, as:

    $ git branch -D Test_Branch
    

    To delete Test_Branch from remote as well, execute:

    git push origin --delete Test_Branch
    

    Can you center a Button in RelativeLayout?

    It's pretty simple, just use Android:CenterInParent="true" to center both in horizontal and vertical, or use Android:Horizontal="true" to center in horizontal and Android:Vertical="true"

    And make sure you write all this in RelaytiveLayout

    MySQL WHERE IN ()

    you must have record in table or array record in database.

    example:

    SELECT * FROM tabel_record
    WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);
    

    JavaScript: Difference between .forEach() and .map()

    Difference between forEach() & map()

    forEach() just loop through the elements. It's throws away return values and always returns undefined.The result of this method does not give us an output .

    map() loop through the elements allocates memory and stores return values by iterating main array

    Example:

       var numbers = [2,3,5,7];
    
       var forEachNum = numbers.forEach(function(number){
          return number
       })
       console.log(forEachNum)
       //output undefined
    
       var mapNum = numbers.map(function(number){
          return number
       })
       console.log(mapNum)
       //output [2,3,5,7]
    

    map() is faster than forEach()

    What is time_t ultimately a typedef to?

    Under Visual Studio 2008, it defaults to an __int64 unless you define _USE_32BIT_TIME_T. You're better off just pretending that you don't know what it's defined as, since it can (and will) change from platform to platform.

    How do I delete NuGet packages that are not referenced by any project in my solution?

    Solution 1

    Use the powershell pipeline to get packages and remove in single statement like this

    Get-Package | Uninstall-Package
    

    Solution 2

    if you want to uninstall selected packages follow these steps

    1. Use GetPackages to get the list of packages
    2. Download Nimble text software
    3. Copy the output of GetPackages in NimbleText(For each row in the list window)
    4. Set Column Seperator to ( if required
    5. Type Uninstall-Package $0 (Substitute using pattern window)
    6. Copy the results and paste them in Package Manage Console

    That be all folks.

    How do I catch a numpy warning like it's an exception (not just for testing)?

    To add a little to @Bakuriu's answer:

    If you already know where the warning is likely to occur then it's often cleaner to use the numpy.errstate context manager, rather than numpy.seterr which treats all subsequent warnings of the same type the same regardless of where they occur within your code:

    import numpy as np
    
    a = np.r_[1.]
    with np.errstate(divide='raise'):
        try:
            a / 0   # this gets caught and handled as an exception
        except FloatingPointError:
            print('oh no!')
    a / 0           # this prints a RuntimeWarning as usual
    

    Edit:

    In my original example I had a = np.r_[0], but apparently there was a change in numpy's behaviour such that division-by-zero is handled differently in cases where the numerator is all-zeros. For example, in numpy 1.16.4:

    all_zeros = np.array([0., 0.])
    not_all_zeros = np.array([1., 0.])
    
    with np.errstate(divide='raise'):
        not_all_zeros / 0.  # Raises FloatingPointError
    
    with np.errstate(divide='raise'):
        all_zeros / 0.  # No exception raised
    
    with np.errstate(invalid='raise'):
        all_zeros / 0.  # Raises FloatingPointError
    

    The corresponding warning messages are also different: 1. / 0. is logged as RuntimeWarning: divide by zero encountered in true_divide, whereas 0. / 0. is logged as RuntimeWarning: invalid value encountered in true_divide. I'm not sure why exactly this change was made, but I suspect it has to do with the fact that the result of 0. / 0. is not representable as a number (numpy returns a NaN in this case) whereas 1. / 0. and -1. / 0. return +Inf and -Inf respectively, per the IEE 754 standard.

    If you want to catch both types of error you can always pass np.errstate(divide='raise', invalid='raise'), or all='raise' if you want to raise an exception on any kind of floating point error.

    TypeError: 'builtin_function_or_method' object is not subscriptable

    Looks like you typed brackets instead of parenthesis by mistake.

    sql query to find the duplicate records

    You can do it in a single query:

    Select t.Id, t.title, z.dupCount
    From yourtable T
    Join
       (select title, Count (*) dupCount
        from yourtable 
        group By title
        Having Count(*) > 1) z
       On z.title = t.Title
    order By dupCount Desc
    

    Regex for string contains?

    Just don't anchor your pattern:

    /Test/
    

    The above regex will check for the literal string "Test" being found somewhere within it.

    html table cell width for different rows

    As far as i know that is impossible and that makes sense since what you are trying to do is against the idea of tabular data presentation. You could however put the data in multiple tables and remove any padding and margins in between them to achieve the same result, at least visibly. Something along the lines of:

    _x000D_
    _x000D_
    <html>_x000D_
    _x000D_
    <head>_x000D_
      <style type="text/css">_x000D_
        .mytable {_x000D_
          border-collapse: collapse;_x000D_
          width: 100%;_x000D_
          background-color: white;_x000D_
        }_x000D_
        .mytable-head {_x000D_
          border: 1px solid black;_x000D_
          margin-bottom: 0;_x000D_
          padding-bottom: 0;_x000D_
        }_x000D_
        .mytable-head td {_x000D_
          border: 1px solid black;_x000D_
        }_x000D_
        .mytable-body {_x000D_
          border: 1px solid black;_x000D_
          border-top: 0;_x000D_
          margin-top: 0;_x000D_
          padding-top: 0;_x000D_
          margin-bottom: 0;_x000D_
          padding-bottom: 0;_x000D_
        }_x000D_
        .mytable-body td {_x000D_
          border: 1px solid black;_x000D_
          border-top: 0;_x000D_
        }_x000D_
        .mytable-footer {_x000D_
          border: 1px solid black;_x000D_
          border-top: 0;_x000D_
          margin-top: 0;_x000D_
          padding-top: 0;_x000D_
        }_x000D_
        .mytable-footer td {_x000D_
          border: 1px solid black;_x000D_
          border-top: 0;_x000D_
        }_x000D_
      </style>_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
      <table class="mytable mytable-head">_x000D_
        <tr>_x000D_
          <td width="25%">25</td>_x000D_
          <td width="50%">50</td>_x000D_
          <td width="25%">25</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
      <table class="mytable mytable-body">_x000D_
        <tr>_x000D_
          <td width="50%">50</td>_x000D_
          <td width="30%">30</td>_x000D_
          <td width="20%">20</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
      <table class="mytable mytable-body">_x000D_
        <tr>_x000D_
          <td width="16%">16</td>_x000D_
          <td width="68%">68</td>_x000D_
          <td width="16%">16</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
      <table class="mytable mytable-footer">_x000D_
        <tr>_x000D_
          <td width="20%">20</td>_x000D_
          <td width="30%">30</td>_x000D_
          <td width="50%">50</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    JSFIDDLE

    I don't know your requirements but i'm sure there's a more elegant solution.

    Convert a double to a QString

    Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(...) function. For instance, I wanted 3 decimal places:

    double value = 34.0495834;
    QString strValue = QString::number(value, 'f', 3);
    // strValue == "34.050"
    

    The 'f' specifies decimal format notation (more info here, you can also specify scientific notation) and the 3 specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number function can be found here in the QString documentation

    JSON datetime between Python and JavaScript

    Using json, you can subclass JSONEncoder and override the default() method to provide your own custom serializers:

    import json
    import datetime
    
    class DateTimeJSONEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, datetime.datetime):
                return obj.isoformat()
            else:
                return super(DateTimeJSONEncoder, self).default(obj)
    

    Then, you can call it like this:

    >>> DateTimeJSONEncoder().encode([datetime.datetime.now()])
    '["2010-06-15T14:42:28"]'
    

    How can I specify a local gem in my Gemfile?

    You can also reference a local gem with git if you happen to be working on it.

    gem 'foo',
      :git => '/Path/to/local/git/repo',
      :branch => 'my-feature-branch'
    

    Then, if it changes I run

    bundle exec gem uninstall foo
    bundle update foo
    

    But I am not sure everyone needs to run these two steps.

    How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

    You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

    Here is a complete example from your data that shows a bar of for each required value at each date:

    import pylab as pl
    import datetime
    
    data = """0 14-11-2003
    1 15-03-1999
    12 04-12-2012
    33 09-05-2007
    44 16-08-1998
    55 25-07-2001
    76 31-12-2011
    87 25-06-1993
    118 16-02-1995
    119 10-02-1981
    145 03-05-2014"""
    
    values = []
    dates = []
    
    for line in data.split("\n"):
        x, y = line.split()
        values.append(int(x))
        dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())
    
    fig = pl.figure()
    ax = pl.subplot(111)
    ax.bar(dates, values, width=100)
    ax.xaxis_date()
    

    You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

    If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

    fig = pl.figure()
    ax = pl.subplot(111)
    ax.bar(range(len(dates)), values)
    

    EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

    fig = pl.figure()
    ax = pl.subplot(111)
    width=0.8
    ax.bar(range(len(dates)), values, width=width)
    ax.set_xticks(np.arange(len(dates)) + width/2)
    ax.set_xticklabels(dates, rotation=90)
    

    Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

    Since ?99 the matching between format specifiers and floating-point argument types in C is consistent between printf and scanf. It is

    • %f for float
    • %lf for double
    • %Lf for long double

    It just so happens that when arguments of type float are passed as variadic parameters, such arguments are implicitly converted to type double. This is the reason why in printf format specifiers %f and %lf are equivalent and interchangeable. In printf you can "cross-use" %lf with float or %f with double.

    But there's no reason to actually do it in practice. Don't use %f to printf arguments of type double. It is a widespread habit born back in C89/90 times, but it is a bad habit. Use %lf in printf for double and keep %f reserved for float arguments.

    How to add a response header on nginx when using proxy_pass?

    You could try this solution :

    In your location block when you use proxy_pass do something like this:

    location ... {
    
      add_header yourHeaderName yourValue;
      proxy_pass xxxx://xxx_my_proxy_addr_xxx;
    
      # Now use this solution:
      proxy_ignore_headers yourHeaderName // but set by proxy
    
      # Or if above didn't work maybe this:
      proxy_hide_header yourHeaderName // but set by proxy
    
    }
    

    I'm not sure would it be exactly what you need but try some manipulation of this method and maybe result will fit your problem.

    Also you can use this combination:

    proxy_hide_header headerSetByProxy;
    set $sent_http_header_set_by_proxy yourValue;
    

    python 2 instead of python 3 as the (temporary) default python?

    You could use alias python="/usr/bin/python2.7":

    bash-3.2$ alias
    bash-3.2$ python
    Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
    [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> ^D
    bash-3.2$ alias python="/usr/bin/python3.3"
    bash-3.2$ python
    Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35) 
    [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 
    

    hide/show a image in jquery

    If you're trying to hide upload img and show bandwidth img on bandwidth click and viceversa this would work

    <script>
    
        function show_img(id)
        {
            if(id=='bandwidth')
            {
               $("#upload").hide();
               $("#bandwith").show();
            }
            else if(id=='upload')
            {
                $("#upload").show();
                $("#bandwith").hide();
            }
        return false;
         } 
        </script>
        <a href="#" onclick="javascript:show_img('bandwidth');">Bandwidth</a>
        <a href="#" onclick="javascript:show_img('upload');">Upload</a>
        <p align="center"> 
          <img src="/media/img/close.png" style="visibility: hidden;" id="bandwidth"/>
          <img src="/media/img/close.png" style="visibility: hidden;" id="upload"/>
        </p>
    

    RegEx for Javascript to allow only alphanumeric

    If you wanted to return a replaced result, then this would work:

    var a = 'Test123*** TEST';
    var b = a.replace(/[^a-z0-9]/gi,'');
    console.log(b);
    

    This would return:

    Test123TEST
    

    Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I have a-z instead of a-zA-Z. And the ^ inside the brackets means "anything not in these brackets".

    WARNING: Alphanumeric is great if that's exactly what you want. But if you're using this in an international market on like a person's name or geographical area, then you need to account for unicode characters, which this won't do. For instance, if you have a name like "Âlvarö", it would make it "lvar".

    What are the options for storing hierarchical data in a relational database?

    This is really a square peg, round hole question.

    If relational databases and SQL are the only hammer you have or are willing to use, then the answers that have been posted thus far are adequate. However, why not use a tool designed to handle hierarchical data? Graph database are ideal for complex hierarchical data.

    The inefficiencies of the relational model along with the complexities of any code/query solution to map a graph/hierarchical model onto a relational model is just not worth the effort when compared to the ease with which a graph database solution can solve the same problem.

    Consider a Bill of Materials as a common hierarchical data structure.

    class Component extends Vertex {
        long assetId;
        long partNumber;
        long material;
        long amount;
    };
    
    class PartOf extends Edge {
    };
    
    class AdjacentTo extends Edge {
    };
    

    Shortest path between two sub-assemblies: Simple graph traversal algorithm. Acceptable paths can be qualified based on criteria.

    Similarity: What is the degree of similarity between two assemblies? Perform a traversal on both sub-trees computing the intersection and union of the two sub-trees. The percent similar is the intersection divided by the union.

    Transitive Closure: Walk the sub-tree and sum up the field(s) of interest, e.g. "How much aluminum is in a sub-assembly?"

    Yes, you can solve the problem with SQL and a relational database. However, there are much better approaches if you are willing to use the right tool for the job.

    How do I set up Visual Studio Code to compile C++ code?

    To Build/run C++ projects in VS code , you manually need to configure tasks.json file which is in .vscode folder in workspace folder . To open tasks.json , press ctrl + shift + P , and type Configure tasks , and press enter, it will take you to tasks.json

    Here i am providing my tasks.json file with some comments to make the file more understandable , It can be used as a reference for configuring tasks.json , i hope it will be useful

    tasks.json

    {
        "version": "2.0.0",
    
        "tasks": [
    
            {
                "label": "build & run",     //It's name of the task , you can have several tasks 
                "type": "shell",    //type can be either 'shell' or 'process' , more details will be given below
                "command": "g++",   
                "args": [
                    "-g",   //gnu debugging flag , only necessary if you want to perform debugging on file  
                    "${file}",  //${file} gives full path of the file
                    "-o",   
                    "${workspaceFolder}\\build\\${fileBasenameNoExtension}",    //output file name
                    "&&",   //to join building and running of the file
                    "${workspaceFolder}\\build\\${fileBasenameNoExtension}"
                ],
                "group": {
                    "kind": "build",    //defines to which group the task belongs
                    "isDefault": true
                },
                "presentation": {   //Explained in detail below
                    "echo": false,
                    "reveal": "always",
                    "focus": true,
                    "panel": "shared",
                    "clear": false,
                    "showReuseMessage": false
                },
                "problemMatcher": "$gcc"
            },
    
        ]
    }
    

    Now , stating directly from the VS code tasks documentation

    description of type property :

    • type: The task's type. For a custom task, this can either be shell or process. If shell is specified, the command is interpreted as a shell command (for example: bash, cmd, or PowerShell). If process is specified, the command is interpreted as a process to execute.

    The behavior of the terminal can be controlled using the presentation property in tasks.json . It offers the following properties:

    • reveal: Controls whether the Integrated Terminal panel is brought to front. Valid values are:

      • always - The panel is always brought to front. This is the default
      • never - The user must explicitly bring the terminal panel to the front using the View > Terminal command (Ctrl+`).
      • silent - The terminal panel is brought to front only if the output is not scanned for errors and warnings.
    • focus: Controls whether the terminal is taking input focus or not. Default is false.

    • echo: Controls whether the executed command is echoed in the terminal. Default is true.
    • showReuseMessage: Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.
    • panel: Controls whether the terminal instance is shared between task runs. Possible values are:
      • shared: The terminal is shared and the output of other task runs are added to the same terminal.
      • dedicated: The terminal is dedicated to a specific task. If that task is executed again, the terminal is reused. However, the output of a different task is presented in a different terminal.
      • new: Every execution of that task is using a new clean terminal.
    • clear: Controls whether the terminal is cleared before this task is run. Default is false.

    Making a list of evenly spaced numbers in a certain range in python

    You can use the following approach:

    [lower + x*(upper-lower)/length for x in range(length)]
    

    lower and/or upper must be assigned as floats for this approach to work.

    Ways to eliminate switch in code

    Why do you want to? In the hands of a good compiler, a switch statement can be far more efficient than if/else blocks (as well as being easier to read), and only the largest switches are likely to be sped up if they're replaced by any sort of indirect-lookup data structure.

    Unique constraint violation during insert: why? (Oracle)

    Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.

    CREATE TABLE [DB] (
        [DBId] bigint NOT NULL IDENTITY,
        ...
    
        CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),
    
    ); 
    

    How to stop C# console applications from closing automatically?

    Those solutions mentioned change how your program work.

    You can off course put #if DEBUG and #endif around the Console calls, but if you really want to prevent the window from closing only on your dev machine under Visual Studio or if VS isn't running only if you explicitly configure it, and you don't want the annoying 'Press any key to exit...' when running from the command line, the way to go is to use the System.Diagnostics.Debugger API's.

    If you only want that to work in DEBUG, simply wrap this code in a [Conditional("DEBUG")] void BreakConditional() method.

    // Test some configuration option or another
    bool launch;
    var env = Environment.GetEnvironmentVariable("LAUNCH_DEBUGGER_IF_NOT_ATTACHED");
    if (!bool.TryParse(env, out launch))
        launch = false;
    
    // Break either if a debugger is already attached, or if configured to launch
    if (launch || Debugger.IsAttached) {
        if (Debugger.IsAttached || Debugger.Launch())
            Debugger.Break();
    }
    

    This also works to debug programs that need elevated privileges, or that need to be able to elevate themselves.

    Why does flexbox stretch my image rather than retaining aspect ratio?

    The key attribute is align-self: center:

    _x000D_
    _x000D_
    .container {_x000D_
      display: flex;_x000D_
      flex-direction: column;_x000D_
    }_x000D_
    _x000D_
    img {_x000D_
      max-width: 100%;_x000D_
    }_x000D_
    _x000D_
    img.align-self {_x000D_
      align-self: center;_x000D_
    }
    _x000D_
    <div class="container">_x000D_
        <p>Without align-self:</p>_x000D_
        <img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
        <p>With align-self:</p>_x000D_
        <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Visual Studio: Relative Assembly References Paths

    As mentioned before, you can manually edit your project's .csproj file in order to apply it manually.

    I also noticed that Visual Studio 2013 attempts to apply a relative path to the reference hintpath, probably because of an attempt to make the project file more portable.

    What is the difference between square brackets and parentheses in a regex?

    The first 2 examples act very differently if you are REPLACING them by something. If you match on this:

    str = str.replace(/^(7|8|9)/ig,''); 
    

    you would replace 7 or 8 or 9 by the empty string.

    If you match on this

    str = str.replace(/^[7|8|9]/ig,''); 
    

    you will replace 7 or 8 or 9 OR THE VERTICAL BAR!!!! by the empty string.

    I just found this out the hard way.

    How to extract table as text from the PDF using Python?

    If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

    import camelot
    tables = camelot.read_pdf('foo.pdf')
    

    You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

    tables.export('foo.csv', f='csv', compress=False)
    

    Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

    import camelot
    import cProfile
    import pstats
    import tabula
    
    cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
    prof_tabula = cProfile.Profile().run(cmd_tabula)
    time_tabula = pstats.Stats(prof_tabula).total_tt
    
    cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
    prof_camelot = cProfile.Profile().run(cmd_camelot)
    time_camelot = pstats.Stats(prof_camelot).total_tt
    
    print(time_tabula, time_camelot, time_camelot/time_tabula)
    

    gave

    1.8495559890000015 11.057014036000016 5.978199147125147
    

    How do you get the length of a string?

    In some cases String.length might return a value which is different from the actual number of characters visible on the screen (e.g. some emojis are encoded by 2 UTF-16 units):

    MDN says: This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.

    Python Matplotlib Y-Axis ticks on Right Side of Plot

    Use ax.yaxis.tick_right()

    for example:

    from matplotlib import pyplot as plt
    
    f = plt.figure()
    ax = f.add_subplot(111)
    ax.yaxis.tick_right()
    plt.plot([2,3,4,5])
    plt.show()
    

    enter image description here

    How to get start and end of previous month in VB

    firstDay = DateSerial(Year(DateAdd("m", -1, Now)), Month(DateAdd("m", -1, Now)), 1)
    lastDay = DateAdd("d", -1, DateSerial(Year(Now), Month(Now), 1))
    

    This is another way to do it, but I think Remou's version looks cleaner.

    Setting up maven dependency for SQL Server

    Be careful with the answers above. sqljdbc4.jar is not distributed with under a public license which is why it is difficult to include it in a jar for runtime and distribution. See my answer below for more details and a much better solution. Your life will become much easier as mine did once I found this answer.

    https://stackoverflow.com/a/30111956/3368958

    Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

    First import FormsModule from angular lib and under NgModule declared it in imports

    import { FormsModule } from '@angular/forms';
        @NgModule({
          declarations: [
            AppComponent,
            ],
          imports: [
            BrowserModule,
            FormsModule
          ],
          providers: [],
          bootstrap: [AppComponent]
        })
    

    Label axes on Seaborn Barplot

    Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:

    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
    ax = sns.barplot(x = 'val', y = 'cat', 
                  data = fake, 
                  color = 'black')
    ax.set(xlabel='common xlabel', ylabel='common ylabel')
    plt.show()
    

    javascript object max size limit

    you have to put this in web.config :

    <system.web.extensions>
        <scripting>
          <webServices>
            <jsonSerialization maxJsonLength="50000000" />
          </webServices>
        </scripting>
      </system.web.extensions>
    

    JavaScript private methods

    I conjured up this: EDIT: Actually, someone has linked to a identical solution. Duh!

    var Car = function() {
    }
    
    Car.prototype = (function() {
        var hotWire = function() {
            // Private code *with* access to public properties through 'this'
            alert( this.drive() ); // Alerts 'Vroom!'
        }
    
        return {
            steal: function() {
                hotWire.call( this ); // Call a private method
            },
            drive: function() {
                return 'Vroom!';
            }
        };
    })();
    
    var getAwayVechile = new Car();
    
    hotWire(); // Not allowed
    getAwayVechile.hotWire(); // Not allowed
    getAwayVechile.steal(); // Alerts 'Vroom!'
    

    std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

    They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes :

    lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.

    And

    unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

    Here is an example implemetation :

    #include <iostream>
    #include <thread>
    #include <mutex>
    #include <condition_variable>
    #include <functional>
    #include <chrono>
    
    using namespace std::chrono;
    
    class Product{
    
       public:
    
           Product(int data):mdata(data){
           }
    
           virtual~Product(){
           }
    
           bool isReady(){
           return flag;
           }
    
           void showData(){
    
            std::cout<<mdata<<std::endl;
           }
    
           void read(){
    
             std::this_thread::sleep_for(milliseconds(2000));
    
             std::lock_guard<std::mutex> guard(mmutex);
    
             flag = true;
    
             std::cout<<"Data is ready"<<std::endl;
    
             cvar.notify_one();
    
           }
    
           void task(){
    
           std::unique_lock<std::mutex> lock(mmutex);
    
           cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });
    
           mdata+=1;
    
           }
    
       protected:
    
        std::condition_variable cvar;
        std::mutex mmutex;
        int mdata;
        bool flag = false;
    
    };
    
    int main(){
    
         int a = 0;
         Product product(a);
    
         std::thread reading(product.read, &product);
         std::thread setting(product.task, &product);
    
         reading.join();
         setting.join();
    
    
         product.showData();
        return 0;
    }
    

    In this example, i used the unique_lock<muType> with condition variable

    How best to read a File into List<string>

    Why not use a generator instead?

    private IEnumerable<string> ReadLogLines(string logPath) {
        using(StreamReader reader = File.OpenText(logPath)) {
            string line = "";
            while((line = reader.ReadLine()) != null) {
                yield return line;
            }
        }
    }
    

    Then you can use it like you would use the list:

    var logFile = ReadLogLines(LOG_PATH);
    foreach(var s in logFile) {
        // Do whatever you need
    }
    

    Of course, if you need to have a List<string>, then you will need to keep the entire file contents in memory. There's really no way around that.

    Best way to compare 2 XML documents in Java

    Below code works for me

    String xml1 = ...
    String xml2 = ...
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLAssert.assertXMLEqual(actualxml, xmlInDb);
    

    Changing project port number in Visual Studio 2013

    To specify a port for the ASP.NET Development Server

    • In Solution Explorer, click the name of the application.

    • In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list.

    • This will enable editing of the Port number property.

    • In the Properties pane, click the text box beside Port number and
      type in a port number. Click outside of the Properties pane. This
      saves the property settings.

    • Each time you run a file-system Web site within Visual Web Developer, the ASP.NET Development Server will listen on the specified port.

    Hope this helps.

    Refresh Page C# ASP.NET

    To refresh the whole page, but it works normally:

    Response.Redirect(url,bool) 
    

    pip install - locale.Error: unsupported locale setting

    The root cause is: your environment variable LC_ALL is missing or invalid somehow

    Short answer-

    just run the following command:

    $ export LC_ALL=C
    

    If you keep getting the error in new terminal windows, add it at the bottom of your .bashrc file.

    Long answer-

    Here is my locale settings:

    $ locale
    LANG=en_US.UTF-8
    LANGUAGE=
    LC_CTYPE="C"
    LC_NUMERIC="C"
    LC_TIME="C"
    LC_COLLATE="C"
    LC_MONETARY="C"
    LC_MESSAGES="C"
    LC_PAPER="C"
    LC_NAME="C"
    LC_ADDRESS="C"
    LC_TELEPHONE="C"
    LC_MEASUREMENT="C"
    LC_IDENTIFICATION="C"
    LC_ALL=C
    

    Python2.7

        $ uname -a
        Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
        $ python --version
        Python 2.7.9
        $ pip --version
        pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
        $ unset LC_ALL
        $ pip install virtualenv
        Traceback (most recent call last):
          File "/usr/local/bin/pip", line 11, in <module>
            sys.exit(main())
          File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
            locale.setlocale(locale.LC_ALL, '')
          File "/usr/lib/python2.7/locale.py", line 579, in setlocale
            return _setlocale(category, locale)
        locale.Error: unsupported locale setting
        $ export LC_ALL=C
        $ pip install virtualenv
        Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages
    

    VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

    Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.

    Styling text input caret

    In CSS3, there is now a native way to do this, without any of the hacks suggested in the existing answers: the caret-color property.

    There are a lot of things you can do to with the caret, as seen below. It can even be animated.

    /* Keyword value */
    caret-color: auto;
    color: transparent;
    color: currentColor;
    
    /* <color> values */
    caret-color: red;
    caret-color: #5729e9;
    caret-color: rgb(0, 200, 0);
    caret-color: hsla(228, 4%, 24%, 0.8);
    

    The caret-color property is supported from Firefox 55, and Chrome 60. Support is also available in the Safari Technical Preview and in Opera (but not yet in Edge). You can view the current support tables here.

    angularjs ng-style: background-image isn't working

    Just for the records you can also define your object in the controller like this:

    this.styleDiv = {color: '', backgroundColor:'', backgroundImage : '' };
    

    and then you can define a function to change the property of the object directly:

    this.changeBackgroundImage = function (){
            this.styleDiv.backgroundImage = 'url('+this.backgroundImage+')';
        }
    

    Doing it in that way you can modify dinamicaly your style.

    Convert ASCII TO UTF-8 Encoding

    Use utf8_encode()

    Man page can be found here http://php.net/manual/en/function.utf8-encode.php

    Also read this article from Joel on Software. It provides an excellent explanation if what Unicode is and how it works. http://www.joelonsoftware.com/articles/Unicode.html

    Extract a substring according to a pattern

    If you are using data.table then tstrsplit() is a natural choice:

    tstrsplit(string, ":")[[2]]
    [1] "E001" "E002" "E003"
    

    jQuery .get error response function?

    You can get detail error by using responseText property.

    $.ajaxSetup({
    error: function(xhr, status, error) {
    alert("An AJAX error occured: " + status + "\nError: " + error + "\nError detail: " + xhr.responseText);
         } 
        });
    

    How may I sort a list alphabetically using jQuery?

    If you are using jQuery you can do this:

    _x000D_
    _x000D_
    $(function() {_x000D_
    _x000D_
      var $list = $("#list");_x000D_
    _x000D_
      $list.children().detach().sort(function(a, b) {_x000D_
        return $(a).text().localeCompare($(b).text());_x000D_
      }).appendTo($list);_x000D_
    _x000D_
    });
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
    _x000D_
    <ul id="list">_x000D_
      <li>delta</li>_x000D_
      <li>cat</li>_x000D_
      <li>alpha</li>_x000D_
      <li>cat</li>_x000D_
      <li>beta</li>_x000D_
      <li>gamma</li>_x000D_
      <li>gamma</li>_x000D_
      <li>alpha</li>_x000D_
      <li>cat</li>_x000D_
      <li>delta</li>_x000D_
      <li>bat</li>_x000D_
      <li>cat</li>_x000D_
    </ul>
    _x000D_
    _x000D_
    _x000D_

    Note that returning 1 and -1 (or 0 and 1) from the compare function is absolutely wrong.

    How to generate components in a specific folder with Angular CLI?

    Quick, Simple and Error free method

    i.e. You want to create a component in a app/common folder as shown in the image given below, then follow these steps

    1. Right click on the folder in which you want to create component.
    2. Select option Open in Integrated Terminal or Open in Command Prompt.
    3. In new terminal (you'll see your selected path), then type ng g c my-component

    Also you can check this process through this image enter image description here

    Communicating between a fragment and an activity - best practices

    There is the latest techniques to communicate fragment to activity without any interface follow the steps Step 1- Add the dependency in gradle

    implementation 'androidx.fragment:fragment:1.3.0-rc01'

    jQuery to loop through elements with the same class

    Use each: 'i' is the postion in the array, obj is the DOM object that you are iterating (can be accessed through the jQuery wrapper $(this) as well).

    $('.testimonial').each(function(i, obj) {
        //test
    });
    

    Check the api reference for more information.

    delete map[key] in go?

    Strangely enough,

    package main
    
    func main () {
        var sessions = map[string] chan int{};
        delete(sessions, "moo");
    }
    

    seems to work. This seems a poor use of resources though!

    Another way is to check for existence and use the value itself:

    package main
    
    func main () {
        var sessions = map[string] chan int{};
        sessions["moo"] = make (chan int);
        _, ok := sessions["moo"];
        if ok {
            delete(sessions, "moo");
        }
    }
    

    When to use references vs. pointers

    Any performance difference would be so small that it wouldn't justify using the approach that's less clear.

    First, one case that wasn't mentioned where references are generally superior is const references. For non-simple types, passing a const reference avoids creating a temporary and doesn't cause the confusion you're concerned about (because the value isn't modified). Here, forcing a person to pass a pointer causes the very confusion you're worried about, as seeing the address taken and passed to a function might make you think the value changed.

    In any event, I basically agree with you. I don't like functions taking references to modify their value when it's not very obvious that this is what the function is doing. I too prefer to use pointers in that case.

    When you need to return a value in a complex type, I tend to prefer references. For example:

    bool GetFooArray(array &foo); // my preference
    bool GetFooArray(array *foo); // alternative
    

    Here, the function name makes it clear that you're getting information back in an array. So there's no confusion.

    The main advantages of references are that they always contain a valid value, are cleaner than pointers, and support polymorphism without needing any extra syntax. If none of these advantages apply, there is no reason to prefer a reference over a pointer.

    How to fix 'sudo: no tty present and no askpass program specified' error?

    Running shell scripts that have contain sudo commands in them from jenkins might not run as expected. To fix this, follow along

    Simple steps:

    1. On ubuntu based systems, run " $ sudo visudo "

    2. this will open /etc/sudoers file.

    3. If your jenkins user is already in that file, then modify to look like this:

    jenkins ALL=(ALL) NOPASSWD: ALL

    1. save the file

    2. Relaunch your jenkins job

    3. you shouldnt see that error message again :)

    Passing functions with arguments to another function in Python?

    Do you mean this?

    def perform(fun, *args):
        fun(*args)
    
    def action1(args):
        # something
    
    def action2(args):
        # something
    
    perform(action1)
    perform(action2, p)
    perform(action3, p, r)
    

    Value of type 'T' cannot be converted to

    Change this line:

    if (typeof(T) == typeof(string))
    

    For this line:

    if (t.GetType() == typeof(string))
    

    Facebook Architecture

    Well Facebook has undergone MANY many changes and it wasn't originally designed to be efficient. It was designed to do it's job. I have absolutely no idea what the code looks like and you probably won't find much info about it (for obvious security and copyright reasons), but just take a look at the API. Look at how often it changes and how much of it doesn't work properly, anymore, or at all.

    I think the biggest ace up their sleeve is the Hiphop. http://developers.facebook.com/blog/post/358 You can use HipHop yourself: https://github.com/facebook/hiphop-php/wiki

    But if you ask me it's a very ambitious and probably time wasting task. Hiphop only supports so much, it can't simply convert everything to C++. So what does this tell us? Well, it tells us that Facebook is NOT fully taking advantage of the PHP language. It's not using the latest 5.3 and I'm willing to bet there's still a lot that is PHP 4 compatible. Otherwise, they couldn't use HipHop. HipHop IS A GOOD IDEA and needs to grow and expand, but in it's current state it's not really useful for that many people who are building NEW PHP apps.

    There's also PHP to JAVA via things like Resin/Quercus. Again, it doesn't support everything...

    Another thing to note is that if you use any non-standard PHP module, you aren't going to be able to convert that code to C++ or Java either. However...Let's take a look at PHP modules. They are ARE compiled in C++. So if you can build PHP modules that do things (like parse XML, etc.) then you are basically (minus some interaction) working at the same speed. Of course you can't just make a PHP module for every possible need and your entire app because you would have to recompile and it would be much more difficult to code, etc.

    However...There are some handy PHP modules that can help with speed concerns. Though at the end of the day, we have this awesome thing known as "the cloud" and with it, we can scale our applications (PHP included) so it doesn't matter as much anymore. Hardware is becoming cheaper and cheaper. Amazon just lowered it's prices (again) speaking of.

    So as long as you code your PHP app around the idea that it will need to one day scale...Then I think you're fine and I'm not really sure I'd even look at Facebook and what they did because when they did it, it was a completely different world and now trying to hold up that infrastructure and maintain it...Well, you get things like HipHop.

    Now how is HipHop going to help you? It won't. It can't. You're starting fresh, you can use PHP 5.3. I'd highly recommend looking into PHP 5.3 frameworks and all the new benefits that PHP 5.3 brings to the table along with the SPL libraries and also think about your database too. You're most likely serving up content from a database, so check out MongoDB and other types of databases that are schema-less and document-oriented. They are much much faster and better for the most "common" type of web site/app.

    Look at NEW companies like Foursquare and Smugmug and some other companies that are utilizing NEW technology and HOW they are using it. For as successful as Facebook is, I honestly would not look at them for "how" to build an efficient web site/app. I'm not saying they don't have very (very) talented people that work there that are solving (their) problems creatively...I'm also not saying that Facebook isn't a great idea in general and that it's not successful and that you shouldn't get ideas from it....I'm just saying that if you could view their entire source code, you probably wouldn't benefit from it.

    array.select() in javascript

    Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.

    The source code for Array.prototype is posted in MDN

    if (!Array.prototype.filter)
    {
      Array.prototype.filter = function(fun /*, thisp */)
      {
        "use strict";
    
        if (this == null)
          throw new TypeError();
    
        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun != "function")
          throw new TypeError();
    
        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++)
        {
          if (i in t)
          {
            var val = t[i]; // in case fun mutates this
            if (fun.call(thisp, val, i, t))
              res.push(val);
          }
        }
    
        return res;
      };
    }
    

    see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details

    java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

    I used yet another trick to format date with 6-digit precision (microseconds):

    System.out.println(
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.").format(microseconds/1000)
        +String.format("%06d", microseconds%1000000));
    

    This technique can be extended further, to nanoseconds and up.

    How to split a string, but also keep the delimiters?

    Here is a simple clean implementation which is consistent with Pattern#split and works with variable length patterns, which look behind cannot support, and it is easier to use. It is similar to the solution provided by @cletus.

    public static String[] split(CharSequence input, String pattern) {
        return split(input, Pattern.compile(pattern));
    }
    
    public static String[] split(CharSequence input, Pattern pattern) {
        Matcher matcher = pattern.matcher(input);
        int start = 0;
        List<String> result = new ArrayList<>();
        while (matcher.find()) {
            result.add(input.subSequence(start, matcher.start()).toString());
            result.add(matcher.group());
            start = matcher.end();
        }
        if (start != input.length()) result.add(input.subSequence(start, input.length()).toString());
        return result.toArray(new String[0]);
    }
    

    I don't do null checks here, Pattern#split doesn't, why should I. I don't like the if at the end but it is required for consistency with the Pattern#split . Otherwise I would unconditionally append, resulting in an empty string as the last element of the result if the input string ends with the pattern.

    I convert to String[] for consistency with Pattern#split, I use new String[0] rather than new String[result.size()], see here for why.

    Here are my tests:

    @Test
    public void splitsVariableLengthPattern() {
        String[] result = Split.split("/foo/$bar/bas", "\\$\\w+");
        Assert.assertArrayEquals(new String[] { "/foo/", "$bar", "/bas" }, result);
    }
    
    @Test
    public void splitsEndingWithPattern() {
        String[] result = Split.split("/foo/$bar", "\\$\\w+");
        Assert.assertArrayEquals(new String[] { "/foo/", "$bar" }, result);
    }
    
    @Test
    public void splitsStartingWithPattern() {
        String[] result = Split.split("$foo/bar", "\\$\\w+");
        Assert.assertArrayEquals(new String[] { "", "$foo", "/bar" }, result);
    }
    
    @Test
    public void splitsNoMatchesPattern() {
        String[] result = Split.split("/foo/bar", "\\$\\w+");
        Assert.assertArrayEquals(new String[] { "/foo/bar" }, result);
    }
    

    UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

    You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

    Pick an encoding and stick with it:

    f.write(printinfo.encode('utf8') + '\n')
    

    or use io.open() to create a file object that'll encode for you as you write to the file:

    import io
    
    f = io.open(filename, 'w', encoding='utf8')
    

    You may want to read:

    before continuing.

    How to find prime numbers between 0 - 100?

    Here's how I solved it. Rewrote it from Java to JavaScript, so excuse me if there's a syntax error.

    function isPrime (n)
    {
        if (n < 2) return false;
    
        /**
         * An integer is prime if it is not divisible by any prime less than or equal to its square root
         **/
    
        var q = Math.floor(Math.sqrt(n));
    
        for (var i = 2; i <= q; i++)
        {
            if (n % i == 0)
            {
                return false;
            }
        }
    
        return true;
    }
    

    A number, n, is a prime if it isn't divisible by any other number other than by 1 and itself. Also, it's sufficient to check the numbers [2, sqrt(n)].

    one line if statement in php

    Use ternary operator:

    echo (($test == '') ? $redText : '');
    echo $test == '' ? $redText : ''; //removed parenthesis
    

    But in this case you can't use shorter reversed version because it will return bool(true) in first condition.

    echo (($test != '') ?: $redText); //this will not work properly for this case
    

    jquery drop down menu closing by clicking outside

    You can tell any click that bubbles all the way up the DOM to hide the dropdown, and any click that makes it to the parent of the dropdown to stop bubbling.

    /* Anything that gets to the document
       will hide the dropdown */
    $(document).click(function(){
      $("#dropdown").hide();
    });
    
    /* Clicks within the dropdown won't make
       it past the dropdown itself */
    $("#dropdown").click(function(e){
      e.stopPropagation();
    });
    

    Demo: http://jsbin.com/umubad/2/edit

    How does a Breadth-First Search work when looking for Shortest Path?

    I have wasted 3 days
    ultimately solved a graph question
    used for
    finding shortest distance
    using BFS

    Want to share the experience.

    When the (undirected for me) graph has
    fixed distance (1, 6, etc.) for edges
    
    #1
    We can use BFS to find shortest path simply by traversing it
    then, if required, multiply with fixed distance (1, 6, etc.)
    
    #2
    As noted above
    with BFS
    the very 1st time an adjacent node is reached, it is shortest path
    
    #3
    It does not matter what queue you use
       deque/queue(c++) or
       your own queue implementation (in c language)
       A circular queue is unnecessary
    
    #4
    Number of elements required for queue is N+1 at most, which I used
    (dint check if N works)
    here, N is V, number of vertices.
    
    #5
    Wikipedia BFS will work, and is sufficient.
        https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode
    

    I have lost 3 days trying all above alternatives, verifying & re-verifying again and again above
    they are not the issue.
    (Try to spend time looking for other issues, if you dint find any issues with above 5).


    More explanation from the comment below:

          A
         /  \
      B       C
     /\       /\
    D  E     F  G
    

    Assume above is your graph
    graph goes downwards
    For A, the adjacents are B & C
    For B, the adjacents are D & E
    For C, the adjacents are F & G

    say, start node is A

    1. when you reach A, to, B & C the shortest distance to B & C from A is 1

    2. when you reach D or E, thru B, the shortest distance to A & D is 2 (A->B->D)

    similarly, A->E is 2 (A->B->E)

    also, A->F & A->G is 2

    So, now instead of 1 distance between nodes, if it is 6, then just multiply the answer by 6
    example,
    if distance between each is 1, then A->E is 2 (A->B->E = 1+1)
    if distance between each is 6, then A->E is 12 (A->B->E = 6+6)

    yes, bfs may take any path
    but we are calculating for all paths

    if you have to go from A to Z, then we travel all paths from A to an intermediate I, and since there will be many paths we discard all but shortest path till I, then continue with shortest path ahead to next node J
    again if there are multiple paths from I to J, we only take shortest one
    example,
    assume,
    A -> I we have distance 5
    (STEP) assume, I -> J we have multiple paths, of distances 7 & 8, since 7 is shortest
    we take A -> J as 5 (A->I shortest) + 8 (shortest now) = 13
    so A->J is now 13
    we repeat now above (STEP) for J -> K and so on, till we get to Z

    Read this part, 2 or 3 times, and draw on paper, you will surely get what i am saying, best of luck


    Save the console.log in Chrome to a file

    Good news

    Chrome dev tools now allows you to save the console output to a file natively

    1. Open the console
    2. Right-click
    3. Select "save as.."

    save console to file

    Chrome Developer instructions here.

    Check if a column contains text using SQL

    Just try below script:

    Below code works only if studentid column datatype is varchar

    SELECT * FROM STUDENTS WHERE STUDENTID like '%Searchstring%'
    

    How can I get the current directory name in Javascript?

    This one-liner works:

    var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')
    

    Comparing boxed Long values 127 and 128

    Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

    This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).

     For example:
        If we set java.lang.Integer.IntegerCache.high=500;
        then values from -128 to 500 will get cached and 
    
        Integer a=498;
        Integer b=499;
        System.out.println(a==b)
    
        Output will be "true".
    

    Float and Double objects never gets cached.

    Character will get cache from 0 to 127

    You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.

    1) type cast both objects into primitive values and compare

        (long)val3 == (long)val4
    

    2) read value of object and compare

        val3.longValue() == val4.longValue()
    

    3) Use equals() method on object comparison.

        val3.equals(val4);  
    

    Indirectly referenced from required .class file

    How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project?

    If you right click on your project and choose build path->configure build path and then choose the libraries tab. You should see the weblogic libraries associated here. If you do not you can click Add Library->Server Runtime. If the library is not there, then you first need to configure it. Windows->Preferences->Server->Installed runtimes

    Find a file by name in Visual Studio Code

    Press Ctl+T will open a search box. Delete # symbol and enter your file name.