Programs & Examples On #Boost thread

Boost.Thread enables the use of multiple threads of execution with shared data in portable C++ code.

Example for boost shared_mutex (multiple reads/one write)?

Great response by Jim Morris, I stumbled upon this and it took me a while to figure. Here is some simple code that shows that after submitting a "request" for a unique_lock boost (version 1.54) blocks all shared_lock requests. This is very interesting as it seems to me that choosing between unique_lock and upgradeable_lock allows if we want write priority or no priority.

Also (1) in Jim Morris's post seems to contradict this: Boost shared_lock. Read preferred?

#include <iostream>
#include <boost/thread.hpp>

using namespace std;

typedef boost::shared_mutex Lock;
typedef boost::unique_lock< Lock > UniqueLock;
typedef boost::shared_lock< Lock > SharedLock;

Lock tempLock;

void main2() {
    cout << "10" << endl;
    UniqueLock lock2(tempLock); // (2) queue for a unique lock
    cout << "11" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    lock2.unlock();
}

void main() {
    cout << "1" << endl;
    SharedLock lock1(tempLock); // (1) aquire a shared lock
    cout << "2" << endl;
    boost::thread tempThread(main2);
    cout << "3" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(3));
    cout << "4" << endl;
    SharedLock lock3(tempLock); // (3) try getting antoher shared lock, deadlock here
    cout << "5" << endl;
    lock1.unlock();
    lock3.unlock();
}

How to get the separate digits of an int number?

Why don't you do:

String number = String.valueOf(input);
char[] digits = number.toCharArray();

Change navbar text color Bootstrap

this code will work ,

.navbar .navbar-nav > li .navbar-item ,
.navbar .navbar-brand{
                       color: red;
                      }

paste in your css and run if you have a element below

  • define it as .navbar-item class

    eg .

    <li>@Html.ActionLink("Login", "Login", "Home", new { area = "" },
     new { @class = "navbar-item" })</li>
    

    OR

    <li> <button class="navbar-item">hi</button></li>
    
  • Checking session if empty or not

    Check if the session is empty or not in C# MVC Version Lower than 5.

    if (!string.IsNullOrEmpty(Session["emp_num"] as string))
    {
        //cast it and use it
        //business logic
    }
    

    Check if the session is empty or not in C# MVC Version Above 5.

    if(Session["emp_num"] != null)
    {
        //cast it and use it
        //business logic
    }
    

    TypeError: argument of type 'NoneType' is not iterable

    If a function does not return anything, e.g.:

    def test():
        pass
    

    it has an implicit return value of None.

    Thus, as your pick* methods do not return anything, e.g.:

    def pickEasy():
        word = random.choice(easyWords)
        word = str(word)
        for i in range(1, len(word) + 1):
            wordCount.append("_")
    

    the lines that call them, e.g.:

    word = pickEasy()
    

    set word to None, so wordInput in getInput is None. This means that:

    if guess in wordInput:
    

    is the equivalent of:

    if guess in None:
    

    and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

    The fix is to add the return type:

    def pickEasy():
        word = random.choice(easyWords)
        word = str(word)
        for i in range(1, len(word) + 1):
            wordCount.append("_")
        return word
    

    Ajax - 500 Internal Server Error

    The 500 (internal server error) means something went wrong on the server's side. It could be several things, but I would start by verifying that the URL and parameters are correct. Also, make sure that whatever handles the request is expecting the request as a GET and not a POST.

    One useful way to learn more about what's going on is to use a tool like Fiddler which will let you watch all HTTP requests and responses so you can see exactly what you're sending and the server is responding with.

    If you don't have a compelling reason to write your own Ajax code, you would be far better off using a library that handles the Ajax interactions for you. jQuery is one option.

    Determine the size of an InputStream

        try {
            InputStream connInputStream = connection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        int size = connInputStream.available();
    

    int available () Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

    InputStream - Android SDK | Android Developers

    create array from mysql query php

    THE CORRECT WAY ************************ THE CORRECT WAY
    
    while($rows[] = mysqli_fetch_assoc($result));
    array_pop($rows);  // pop the last row off, which is an empty row
    

    What is <scope> under <dependency> in pom.xml for?

    Six Dependency scopes:

    • compile: default scope, classpath is available for both src/main and src/test
    • test: classpath is available for src/test
    • provided: like complie but provided by JDK or a container at runtime
    • runtime: not required for compilation only require at runtime
    • system: provided locally provide classpath
    • import: can only import other POMs into the <dependencyManagement/>, only available in Maven 2.0.9 or later (like java import )

    How to revert the last migration?

    there is a good library to use its called djagno-nomad, although not directly related to the question asked, thought of sharing this,

    scenario: most of the time when switching to project, we feel like it should revert our changes that we did on this current branch, that's what exactly this library does, checkout below

    https://pypi.org/project/django-nomad/

    Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

    You can also get this error if you don't specify center or zoom in your map options.

    Automatic login script for a website on windows machine?

    The code below does just that. The below is a working example to log into a game. I made a similar file to log in into Yahoo and a kurzweilai.net forum.

    Just copy the login form from any webpage's source code. Add value= "your user name" and value = "your password". Normally the -input- elements in the source code do not have the value attribute, and sometime, you will see something like that: value=""

    Save the file as a html on a local machine double click it, or make a bat/cmd file to launch and close them as required.

        <!doctype html>
        <!-- saved from url=(0014)about:internet -->
    
        <html>
        <title>Ikariam Autologin</title>
        </head>
        <body>
        <form id="loginForm" name="loginForm" method="post"    action="http://s666.en.ikariam.com/index.php?action=loginAvatar&function=login">
        <select name="uni_url" id="logServer" class="validate[required]">
        <option  class=""  value="s666.en.ikariam.com" fbUrl=""  cookieName=""  >
                Test_en
        </option>
        </select>
        <input id="loginName" name="name" type="text" value="PlayersName" class="" />
        <input id="loginPassword" name="password" type="password" value="examplepassword" class="" />
        <input type="hidden" id="loginKid" name="kid" value=""/>
                            </form>
      <script>document.loginForm.submit();</script>       
      </body></html>
    

    Note that -script- is just -script-. I found there is no need to specify that is is JavaScript. It works anyway. I also found out that a bare-bones version that contains just two input filds: userName and password also work. But I left a hidded input field etc. just in case. Yahoo mail has a lot of hidden fields. Some are to do with password encryption, and it counts login attempts.

    Security warnings and other staff, like Mark of the Web to make it work smoothly in IE are explained here:

    http://happy-snail.webs.com/autologinintogames.htm

    Counting unique values in a column in pandas dataframe like in Qlik?

    To count unique values in column, say hID of dataframe df, use:

    len(df.hID.unique())
    

    JList add/remove Item

    The best and easiest way to clear a JLIST is:

    myJlist.setListData(new String[0]);
    

    JQuery - $ is not defined

    When using jQuery in asp.net, if you are using a master page and you are loading the jquery source file there, make sure you have the header contentplaceholder after all the jquery script references.

    I had a problem where any pages that used that master page would return '$ is not defined' simply because the incorrect order was making the client side code run before the jquery object was created. So make sure you have:

    <head runat="server">
        <script type="text/javascript" src="Scripts/jquery-VERSION#.js"></script>
        <asp:ContentPlaceHolder id="Header" runat="server"></asp:ContentPlaceHolder>
    </head>
    

    That way the code will run in order and you will be able to run jQuery code on the child pages.

    How to get row count in sqlite using Android?

    Once you get the cursor you can do

    Cursor.getCount()
    

    Stop Excel from automatically converting certain text values to dates

    Still an issue in Microsoft Office 2016 release, rather disturbing for those of us working with gene names such as MARC1, MARCH1, SEPT1 etc. The solution I've found to be the most practical after generating a ".csv" file in R, that will then be opened/shared with Excel users:

    1. Open the CSV file as text (notepad)
    2. Copy it (ctrl+a, ctrl+c).
    3. Paste it in a new excel sheet -it will all paste in one column as long text strings.
    4. Choose/select this column.
    5. Go to Data- "Text to columns...", on the window opened choose "delimited" (next). Check that "comma" is marked (marking it will already show the separation of the data to columns below) (next), in this window you can choose the column you want and mark it as text (instead of general) (Finish).

    HTH

    How to print a list in Python "nicely"

    import json
    some_list = ['one', 'two', 'three', 'four']
    print(json.dumps(some_list, indent=4))
    

    Output:

    [
        "one",
        "two",
        "three",
        "four"
    ]
    

    Importing project into Netbeans

    Try copying the src and web folder in different folder location and create New project with existing sources in Netbeans. This should work. Or remove the nbproject folder as well before importing.

    VBScript How can I Format Date?

    Suggest calling 'Now' only once in the function to guard against the minute, or even the day, changing during the execution of the function.

    Thus:

    Function timeStamp()
        Dim t 
        t = Now
        timeStamp = Year(t) & "-" & _
        Right("0" & Month(t),2)  & "-" & _
        Right("0" & Day(t),2)  & "_" & _  
        Right("0" & Hour(t),2) & _
        Right("0" & Minute(t),2) '    '& _    Right("0" & Second(t),2) 
    End Function
    

    Sum all the elements java arraylist

    Not very hard, just use m.get(i) to get the value from the list.

    public double incassoMargherita()
    {
        double sum = 0;
        for(int i = 0; i < m.size(); i++)
        {
            sum += m.get(i);
        }
        return sum;
    }
    

    Storing an object in state of a React component?

    In addition to kiran's post, there's the update helper (formerly a react addon). This can be installed with npm using npm install immutability-helper

    import update from 'immutability-helper';
    
    var abc = update(this.state.abc, {
       xyz: {$set: 'foo'}
    });
    
    this.setState({abc: abc});
    

    This creates a new object with the updated value, and other properties stay the same. This is more useful when you need to do things like push onto an array, and set some other value at the same time. Some people use it everywhere because it provides immutability.

    If you do this, you can have the following to make up for the performance of

    shouldComponentUpdate: function(nextProps, nextState){
       return this.state.abc !== nextState.abc; 
       // and compare any props that might cause an update
    }
    

    Windows equivalent of $export

    There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

    How to round up integer division and have int result in Java?

    To round up an integer division you can use

    import static java.lang.Math.abs;
    
    public static long roundUp(long num, long divisor) {
        int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
        return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
    }
    

    or if both numbers are positive

    public static long roundUp(long num, long divisor) {
        return (num + divisor - 1) / divisor;
    }
    

    RS256 vs HS256: What's the difference?

    In cryptography there are two types of algorithms used:

    Symmetric algorithms

    A single key is used to encrypt data. When encrypted with the key, the data can be decrypted using the same key. If, for example, Mary encrypts a message using the key "my-secret" and sends it to John, he will be able to decrypt the message correctly with the same key "my-secret".

    Asymmetric algorithms

    Two keys are used to encrypt and decrypt messages. While one key(public) is used to encrypt the message, the other key(private) can only be used to decrypt it. So, John can generate both public and private keys, then send only the public key to Mary to encrypt her message. The message can only be decrypted using the private key.

    HS256 and RS256 Scenario

    These algorithms are NOT used to encrypt/decryt data. Rather they are used to verify the origin or the authenticity of the data. When Mary needs to send an open message to Jhon and he needs to verify that the message is surely from Mary, HS256 or RS256 can be used.

    HS256 can create a signature for a given sample of data using a single key. When the message is transmitted along with the signature, the receiving party can use the same key to verify that the signature matches the message.

    RS256 uses pair of keys to do the same. A signature can only be generated using the private key. And the public key has to be used to verify the signature. In this scenario, even if Jack finds the public key, he cannot create a spoof message with a signature to impersonate Mary.

    What is a Question Mark "?" and Colon ":" Operator Used for?

    Thats an if/else statement equilavent to

    if(row % 2 == 1){
      System.out.print("<");
    }else{
      System.out.print("\r>");
    }
    

    Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

    I wrote a simple library for manipulating the JavaScript date object. You can try this:

    var dateString = timeSolver.getString(new Date(), "YYYY/MM/DD HH:MM:SS.SSS")
    

    Library here: https://github.com/sean1093/timeSolver

    versionCode vs versionName in Android Manifest

    It is indeed based on versionCode and not on versionName. However, I noticed that changing the versionCode in AndroidManifest.xml wasn't enough with Android Studio - Gradle build system. I needed to change it in the build.gradle.

    see if two files have the same content in python

    I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.

    There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can

    • Compare file sizes first, discarding all which doesn't match
    • If file sizes match, compare using the biggest hash you can handle, hashing chunks of files to avoid reading the whole big file

    Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)

    How to set a dropdownlist item as selected in ASP.NET?

    You can set the SelectedValue to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error.

    dropdownlist.ClearSelection();
    dropdownlist.SelectedValue = value;
    

    You can also use ListItemCollection.FindByText or ListItemCollection.FindByValue

    dropdownlist.ClearSelection();  
    dropdownlist.Items.FindByValue(value).Selected = true;
    

    Use the FindByValue method to search the collection for a ListItem with a Value property that contains value specified by the value parameter. This method performs a case-sensitive and culture-insensitive comparison. This method does not do partial searches or wildcard searches. If an item is not found in the collection using this criteria, null is returned, MSDN.

    If you expect that you may be looking for text/value that wont be present in DropDownList ListItem collection then you must check if you get the ListItem object or null from FindByText or FindByValue before you access Selected property. If you try to access Selected when null is returned then you will get NullReferenceException.

    ListItem listItem = dropdownlist.Items.FindByValue(value);
    
    if(listItem != null) 
    {
       dropdownlist.ClearSelection();
       listItem.Selected = true;
    }
    

    Check if table exists

    If using jruby, here is a code snippet to return an array of all tables in a db.

    require "rubygems"
    require "jdbc/mysql"
    Jdbc::MySQL.load_driver
    require "java"
    
    def get_database_tables(connection, db_name)
      md = connection.get_meta_data
      rs = md.get_tables(db_name, nil, '%',["TABLE"])
    
      tables = []
      count = 0
      while rs.next
        tables << rs.get_string(3)
      end #while
      return tables
    end
    

    How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

    This answer, but with storyboard support.

    class SwipeNavigationController: UINavigationController {
    
        // MARK: - Lifecycle
    
        override init(rootViewController: UIViewController) {
            super.init(rootViewController: rootViewController)
        }
    
        override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
            super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    
            self.setup()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
            self.setup()
        }
    
        private func setup() {
            delegate = self
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // This needs to be in here, not in init
            interactivePopGestureRecognizer?.delegate = self
        }
    
        deinit {
            delegate = nil
            interactivePopGestureRecognizer?.delegate = nil
        }
    
        // MARK: - Overrides
    
        override func pushViewController(_ viewController: UIViewController, animated: Bool) {
            duringPushAnimation = true
    
            super.pushViewController(viewController, animated: animated)
        }
    
        // MARK: - Private Properties
    
        fileprivate var duringPushAnimation = false
    }
    

    Python, creating objects

    class Student(object):
        name = ""
        age = 0
        major = ""
    
        # The class "constructor" - It's actually an initializer 
        def __init__(self, name, age, major):
            self.name = name
            self.age = age
            self.major = major
    
    def make_student(name, age, major):
        student = Student(name, age, major)
        return student
    

    Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:

    class Student(object):
        name = ""
        age = 0
        major = ""
    
    def make_student(name, age, major):
        student = Student()
        student.name = name
        student.age = age
        student.major = major
        # Note: I didn't need to create a variable in the class definition before doing this.
        student.gpa = float(4.0)
        return student
    

    I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.

    PHP - Debugging Curl

    To just get the info of a CURL request do this:

    $response = curl_exec($ch);
    
    $info = curl_getinfo($ch);
    var_dump($info);
    

    How to Check whether Session is Expired or not in asp.net

    I use the @Adi-lester answer and add some methods.

    Method to verify if Session is Alive

    public static void SessionIsAlive(HttpSessionStateBase Session)
    {
        if (Session.Contents.Count == 0)
        {
            Response.Redirect("Timeout.html"); 
        }
        else
        {
            InitializeControls();
        }
    }
    

    Create session var in Page Load

    protected void Page_Load(object sender, EventArgs e)
    {
        Session["user_id"] = 1;
    }
    

    Create SaveData method (but you can use it in all methods)

    protected void SaveData()
    {
        // Verify if Session is Alive
        SessionIsAlive(Session);
    
        //Save Data Process
        // bla
        // bla
        // bla
    }
    

    Get the first element of an array

    I imagine the author just was looking for a way to get the first element of an array after getting it from some function (mysql_fetch_row, for example) without generating a STRICT "Only variables should be passed by reference".

    If it so, almost all the ways described here will get this message... and some of them uses a lot of additional memory duplicating an array (or some part of it). An easy way to avoid it is just assigning the value inline before calling any of those functions:

    $first_item_of_array = current($tmp_arr = mysql_fetch_row(...));
    // or
    $first_item_of_array = reset($tmp_arr = func_get_my_huge_array());
    

    This way you don't get the STRICT message on screen, nor in logs, and you don't create any additional arrays. It works with both indexed AND associative arrays.

    Android: How do I get string from resources using its name?

    You can try this in an Activity:

    getResources().getString(R.string.your string name);
    

    In other situations like fragments,... use

    getContext().getResources().getString(R.string.your string name);
    

    How to delete empty folders using windows command prompt?

    You can use the ROBOCOPY command. It is very simple and can also be used to delete empty folders inside large hierarchy.

    ROBOCOPY folder1 folder1 /S /MOVE
    

    Here both source and destination are folder1, as you only need to delete empty folders, instead of moving other(required) files to different folder. /S option is to skip copying(moving - in the above case) empty folders. It is also faster as the files are moved inside the same drive.

    PHP-FPM doesn't write to error log

    There are multiple php config files, but THIS is the one you need to edit:

    /etc/php(version)?/fpm/pool.d/www.conf
    

    uncomment the line that says:

    catch_workers_output
    

    That will allow PHPs stderr to go to php-fpm's error log instead of /dev/null.

    Find a commit on GitHub given the commit hash

    View single commit:
    https://github.com/<user>/<project>/commit/<hash>

    View log:
    https://github.com/<user>/<project>/commits/<hash>

    View full repo:
    https://github.com/<user>/<project>/tree/<hash>

    <hash> can be any length as long as it is unique.

    Get cart item name, quantity all details woocommerce

    you can get the product name like this

    foreach ( $cart_object->cart_contents as  $value ) {
            $_product     = apply_filters( 'woocommerce_cart_item_product', $value['data'] );
    
            if ( ! $_product->is_visible() ) {
                    echo $_product->get_title();
            } else {
                    echo $_product->get_title();
            }
    
    
         }
    

    Converting HTML to XML

    I was successful using tidy command line utility. On linux I installed it quickly with apt-get install tidy. Then the command:

    tidy -q -asxml --numeric-entities yes source.html >file.xml

    gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.

    This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)

    How can I remove the "No file chosen" tooltip from a file input in Chrome?

    This one works for me (at least in Chrome and Firefox):

    <input type="file" accept="image/*" title="&nbsp;"/>
    

    Delete empty lines using sed

    You are most likely seeing the unexpected behavior because your text file was created on Windows, so the end of line sequence is \r\n. You can use dos2unix to convert it to a UNIX style text file before running sed or use

    sed -r "/^\r?$/d"
    

    to remove blank lines whether or not the carriage return is there.

    How to change the colors of a PNG image easily?

    If you are going to be programming an application to do all of this, the process will be something like this:

    1. Convert image from RGB to HSV
    2. adjust H value
    3. Convert image back to RGB
    4. Save image

    Restricting input to textbox: allowing only numbers and decimal point

    document.getElementById('value').addEventListener('keydown', function(e) {
        var key   = e.keyCode ? e.keyCode : e.which;
    
    /*lenght of value to use with index to know how many numbers after.*/
    
        var len = $('#value').val().length;
        var index = $('#value').val().indexOf('.');
        if (!( [8, 9, 13, 27, 46, 110, 190].indexOf(key) !== -1 ||
                        (key == 65 && ( e.ctrlKey || e.metaKey  ) ) ||
                        (key >= 35 && key <= 40) ||
                        (key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) ||
                        (key >= 96 && key <= 105)
                )){
            e.preventDefault();
        }
    
    /*if theres a . count how many and if reachs 2 digits after . it blocks*/ 
    
        if (index > 0) {
            var CharAfterdot = (len + 1) - index;
            if (CharAfterdot > 3) {
    
    /*permits the backsapce to remove :D could be improved*/
    
                if (!(key == 8))
                {
                    e.preventDefault();
                }
    
    /*blocks if you try to add a new . */
    
            }else if ( key == 110) {
                e.preventDefault();
            }
    
    /*if you try to add a . and theres no digit yet it adds a 0.*/
    
        } else if( key == 110&& len==0){
            e.preventDefault();
            $('#value').val('0.');
        }
    });
    

    How to make a DIV always float on the screen in top right corner?

    Use position:fixed, as previously stated, IE6 doesn't recognize position:fixed, but with some css magic you can get IE6 to behave:

    html, body {
        height: 100%;
        overflow:auto;
    }
    body #fixedElement {
        position:fixed !important;
        position: absolute; /*ie6 */
        bottom: 0;
    }
    

    The !important flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement use position:fixed in all browsers but IE, and in IE, position:absolute will take effect with bottom:0. This will simulate position:fixed for IE6

    Issue with Task Scheduler launching a task

    I was having the same issue. I tried with the compatibility option, but in Windows 10 it doesn't show the compatibility option. The following steps solved the problem for me:

    1. I made sure the account with which the task was running had the full access privileges on the file to be executed. (Executed the task and was still not running)
    2. I man taskschd.msc as administrator
    3. I added the account to run the task (whether was it logged or not)
    4. I executed the task and now IT WORKED!

    So somehow setting up the task in taskschd.msc as a regular user wasn't working, even though my account is an admin one.

    Hope this helps anyone having the same issue

    Could not complete the operation due to error 80020101. IE

    I dont know why but it worked for me. If you have comments like

    //Comment
    

    Then it gives this error. To fix this do

    /*Comment*/
    

    Doesn't make sense but it worked for me.

    Qt: How do I handle the event of the user pressing the 'X' (close) button?

    also you can reimplement protected member QWidget::closeEvent()

    void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
    {
        // do what you need here
        // then call parent's procedure
        QWidget::closeEvent(event);
    }
    

    extract part of a string using bash/cut/split

    Using a single Awk:

    ... | awk -F '[/:]' '{print $5}'
    

    That is, using as field separator either / or :, the username is always in field 5.

    To store it in a variable:

    username=$(... | awk -F '[/:]' '{print $5}')
    

    A more flexible implementation with sed that doesn't require username to be field 5:

    ... | sed -e s/:.*// -e s?.*/??
    

    That is, delete everything from : and beyond, and then delete everything up until the last /. sed is probably faster too than awk, so this alternative is definitely better.

    What does the colon (:) operator do?

    It is used in the new short hand for/loop

    final List<String> list = new ArrayList<String>();
    for (final String s : list)
    {
       System.out.println(s);
    }
    

    and the ternary operator

    list.isEmpty() ? true : false;
    

    What does the "undefined reference to varName" in C mean?

    It is very bad style to define external interfaces in .c files. .

    You should do this

    a.h

        extern void doSomething (int    sig);
    

    a.c

        void doSomething (int    sig)
        {
           ... do stuff 
        }
    

    b.c

    #include "a.h"
    .....
    signal(SIGNAL, doSomething); 
    

    .

    How to change Screen buffer size in Windows Command Prompt from batch script

    I know the question is 9 years old, but maybe for someone it will be interested furthermore. According to the question, to change the buffer size only, it can be used Powershell. The shortest command with Powershell is:

    powershell -command "&{(get-host).ui.rawui.buffersize=@{width=155;height=999};}"
    

    Replace the values of width and height with your wanted values.

    But supposedly the reason of your question is to modify the size of command line window without reducing of the buffer size. For that you can use the following command:

    start /b powershell -command "&{$w=(get-host).ui.rawui;$w.buffersize=@{width=177;height=999};$w.windowsize=@{width=155;height=55};}"
    

    There you can modify the size of buffer and window independly. To avoid an error message, consider that the values of buffersize must be bigger or equal to the values of windowsize.

    Additional implemented is the start /b command. The Powershell command sometimes takes a few seconds to execute. With this additional command, Powershell runs parallel and does not significantly delay the processing of the following commands.

    Can't Autowire @Repository annotated interface in Spring Boot

    Sometimes I had the same issues when I forget to add Lombok annotation processor dependency to the maven configuration

    How to run function in AngularJS controller on document ready?

    If you're getting something like getElementById call returns null, it's probably because the function is running, but the ID hasn't had time to load in the DOM.

    Try using Will's answer (towards the top) with a delay. Example:

    angular.module('MyApp', [])
    
    .controller('MyCtrl', [function() {
        $scope.sleep = (time) => {
            return new Promise((resolve) => setTimeout(resolve, time));
        };
        angular.element(document).ready(function () {
            $scope.sleep(500).then(() => {        
                //code to run here after the delay
            });
        });
    }]);
    

    Trigger an event on `click` and `enter`

    $('#form').keydown(function(e){
        if (e.keyCode === 13) { // If Enter key pressed
            $(this).trigger('submit');
        }
    });
    

    What is ANSI format?

    I remember when "ANSI" text referred to the pseudo VT-100 escape codes usable in DOS through the ANSI.SYS driver to alter the flow of streaming text.... Probably not what you are referring to but if it is see http://en.wikipedia.org/wiki/ANSI_escape_code

    Github Push Error: RPC failed; result=22, HTTP code = 413

    I got this problem when I try to clone a git repo in Linux machine.

    the following URL is working for me in windows

    http://[email protected]/scm/project/swamy-main.git
    

    whereas the following URL works in Linux machine and it has https in URL

    https://[email protected]/scm/project/swamy-main.git
    

    Overriding fields or properties in subclasses

    Of the three solutions only Option 1 is polymorphic.

    Fields by themselves cannot be overridden. Which is exactly why Option 2 returns the new keyword warning.

    The solution to the warning is not to append the “new” keyword, but to implement Option 1.

    If you need your field to be polymorphic you need to wrap it in a Property.

    Option 3 is OK if you don’t need polymorphic behavior. You should remember though, that when at runtime the property MyInt is accessed, the derived class has no control on the value returned. The base class by itself is capable of returning this value.

    This is how a truly polymorphic implementation of your property might look, allowing the derived classes to be in control.

    abstract class Parent
    {
        abstract public int MyInt { get; }
    }
    
    class Father : Parent
    {
        public override int MyInt
        {
            get { /* Apply formula "X" and return a value */ }
        }
    }
    
    class Mother : Parent
    {
        public override int MyInt
        {
            get { /* Apply formula "Y" and return a value */ }
        }
    }
    

    Android studio - Failed to find target android-18

    You can solve the problem changing the compileSdkVersion in the Grandle.build file from 18 to wtever SDK is installed ..... BUTTTTT

    1. If you are trying to goin back in SDK versions like 18 to 17 ,You can not use the feature available in 18 or 18+

    2. If you are migrating your project (Eclipse to Android Studio ) Then off course you Don't have build.gradle file in your Existed Eclipse project

    So, the only solution is to ensure the SDK version installed or not, you are targeting to , If not then install.

    Error:Cause: failed to find target with hash string 'android-19' in: C:\Users\setia\AppData\Local\Android\sdk

    Show loading gif after clicking form submit using jQuery

    What about an onclick function:

        <form id="form">
        <input type="text" name="firstInput">
        <button type="button" name="namebutton" 
               onClick="$('#gif').css('visibility', 'visible');
                        $('#form').submit();">
        </form>
    

    Of course you can put this in a function and then trigger it with an onClick

    phpmyadmin "Not Found" after install on Apache, Ubuntu

    It seems like sometime during the second half of 2018 many php packages such as php-mysql and phpmyadmin were removed or changed. I faced that same problem too. So you'll have to download it from another source or find out the new packages

    Release generating .pdb files, why?

    Also, you can utilize crash dumps to debug your software. The customer sends it to you and then you can use it to identify the exact version of your source - and Visual Studio will even pull the right set of debugging symbols (and source if you're set up correctly) using the crash dump. See Microsoft's documentation on Symbol Stores.

    How to include NA in ifelse?

    So, I hear this works:

    Data$X1<-as.character(Data$X1)
    Data$GEOID<-as.character(Data$BLKIDFP00)
    Data<-within(Data,X1<-ifelse(is.na(Data$X1),GEOID,Data$X2)) 
    

    But I admit I have only intermittent luck with it.

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

    Try out cat and sprintf in your for loop.

    eg.

    cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))
    

    See here

    How to create a vector of user defined size but with no predefined values?

    With the constructor:

    // create a vector with 20 integer elements
    std::vector<int> arr(20);
    
    for(int x = 0; x < 20; ++x)
       arr[x] = x;
    

    How can I make PHP display the error instead of giving me 500 Internal Server Error

    Enabling error displaying from PHP code doesn't work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don't know which line. From the console, I use this:

    /var/log/php-fpm# cat www-error.log | grep mycode.php
    

    And I have the output:

    [04-Apr-2016 06:58:27] PHP Parse error:  syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458
    

    This helps me find the line where I have the typo.

    What does 'IISReset' do?

    When you change an ASP.NET website's configuration file, it restarts the application to reflect the changes...

    When you do an IIS reset, that restarts all applications running on that IIS instance.

    Why doesn't java.io.File have a close method?

    Essentially random access file wraps input and output streams in order to manage the random access. You don't open and close a file, you open and close streams to a file.

    Python strptime() and timezones?

    Ran into this exact problem.

    What I ended up doing:

    # starting with date string
    sdt = "20190901"
    std_format = '%Y%m%d'
    
    # create naive datetime object
    from datetime import datetime
    dt = datetime.strptime(sdt, sdt_format)
    
    # extract the relevant date time items
    dt_formatters = ['%Y','%m','%d']
    dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))
    
    # set timezone
    import pendulum
    tz = pendulum.timezone('utc')
    
    dt_tz = datetime(*dt_vals,tzinfo=tz)
    

    How to check variable type at runtime in Go language

    What's wrong with

    func (e *Easy)SetStringOption(option Option, param string)
    func (e *Easy)SetLongOption(option Option, param long)
    

    and so on?

    How to make Bootstrap carousel slider use mobile left/right swipe

    UPDATE:

    I came up with this solution when I was pretty new to web design. Now that I am older and wiser, the answer Liam gave seems to be a better option. See the next top answer; it is a more productive solution.

    I worked on a project recently and this example worked perfectly. I am giving you the link below.

    First you have to add jQuery mobile:

    http://jquerymobile.com/

    This adds the touch functionality, and then you just have to make events such as swipe:

    <script>
    $(document).ready(function() {
       $("#myCarousel").swiperight(function() {
          $(this).carousel('prev');
        });
       $("#myCarousel").swipeleft(function() {
          $(this).carousel('next');
       });
    });
    </script>
    

    The link is below, where you can find the tutorial I used:

    http://lazcreative.com/blog/how-to/how-to-adding-swipe-support-to-bootstraps-carousel/

    jQuery Get Selected Option From Dropdown

    Here is a simple solution:

    var val = $('#mylist option:selected').text()
    

    Check this example: JsFiddle.

    concatenate variables

    Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:

    rem The retail files set
    set FILES_SET="(*.exe *.dll"
    
    rem The debug extras files set
    set DEBUG_EXTRA=" *.pdb"
    
    rem Build the DEBUG set without any
    set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%
    
    rem Append the closing bracket
    set FILES_SET=%FILES_SET%)
    
    echo %FILES_SET%
    

    Cheers...

    C - gettimeofday for computing time?

    To subtract timevals:

    gettimeofday(&t0, 0);
    /* ... */
    gettimeofday(&t1, 0);
    long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;
    

    This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:

    long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;
    

    Python element-wise tuple operations like sum

    Using all built-ins..

    tuple(map(sum, zip(a, b)))
    

    Ways to eliminate switch in code

    In JavaScript using Associative array:
    this:

    function getItemPricing(customer, item) {
        switch (customer.type) {
            // VIPs are awesome. Give them 50% off.
            case 'VIP':
                return item.price * item.quantity * 0.50;
    
                // Preferred customers are no VIPs, but they still get 25% off.
            case 'Preferred':
                return item.price * item.quantity * 0.75;
    
                // No discount for other customers.
            case 'Regular':
            case
            default:
                return item.price * item.quantity;
        }
    }
    

    becomes this:

    function getItemPricing(customer, item) {
    var pricing = {
        'VIP': function(item) {
            return item.price * item.quantity * 0.50;
        },
        'Preferred': function(item) {
            if (item.price <= 100.0)
                return item.price * item.quantity * 0.75;
    
            // Else
            return item.price * item.quantity;
        },
        'Regular': function(item) {
            return item.price * item.quantity;
        }
    };
    
        if (pricing[customer.type])
            return pricing[customer.type](item);
        else
            return pricing.Regular(item);
    }
    

    Courtesy

    Javascript loading CSV file into an array

    This is what I used to use a csv file into an array. Couldn't get the above answers to work, but this worked for me.

    $(document).ready(function() {
       "use strict";
        $.ajax({
            type: "GET",
            url: "../files/icd10List.csv",
            dataType: "text",
            success: function(data) {processData(data);}
         });
    });
    
    function processData(icd10Codes) {
        "use strict";
        var input = $.csv.toArrays(icd10Codes);
        $("#test").append(input);
    }
    

    Used the jQuery-CSV Plug-in linked above.

    Printing an array in C++?

    May I suggest using the fish bone operator?

    for (auto x = std::end(a); x != std::begin(a); )
    {
        std::cout <<*--x<< ' ';
    }
    

    (Can you spot it?)

    javascript /jQuery - For Loop

    What about something like this?

    var arr = [];
    
    $('[id^=event]', response).each(function(){
        arr.push($(this).html());
    });
    

    The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

    How do I install Python 3 on an AWS EC2 instance?

    Here are the steps I used to manually install python3 for anyone else who wants to do it as it's not super straight forward. EDIT: It's almost certainly easier to use the yum package manager (see other answers).

    Note, you'll probably want to do sudo yum groupinstall 'Development Tools' before doing this otherwise pip won't install.

    wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
    tar zxvf Python-3.4.2.tgz
    cd Python-3.4.2
    sudo yum install gcc
    ./configure --prefix=/opt/python3
    make
    sudo yum install openssl-devel
    sudo make install
    sudo ln -s /opt/python3/bin/python3 /usr/bin/python3
    python3 (should start the interpreter if it's worked (quit() to exit)
    

    Group by in LINQ

    An alternative way to do this could be select distinct PersonId and group join with persons:

    var result = 
        from id in persons.Select(x => x.PersonId).Distinct()
        join p2 in persons on id equals p2.PersonId into gr // apply group join here
        select new 
        {
            PersonId = id,
            Cars = gr.Select(x => x.Car).ToList(),
        };
    

    Or the same with fluent API syntax:

    var result = persons.Select(x => x.PersonId).Distinct()
        .GroupJoin(persons, id => id, p => p.PersonId, (id, gr) => new
        {
            PersonId = id,
            Cars = gr.Select(x => x.Car).ToList(),
        });
    

    GroupJoin produces a list of entries in the first list ( list of PersonId in our case), each with a group of joined entries in the second list (list of persons).

    Python Image Library fails with message "decoder JPEG not available" - PIL

    For those on Mac OS Mountain Lion, I followed the anwser of zeantsoi, but it doesn't work.

    I finally ended up with the solution of this post: http://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/

    Now, I'm happily running my script for jpeg !

    Where does flask look for image files?

    It took me a while to figure this out too. url_for in Flask looks for endpoints that you specified in the routes.py script.

    So if you have a decorator in your routes.py file like @blah.route('/folder.subfolder') then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }} . The 'folder.subfolder' argument sends it to a Flask endpoint it recognizes.

    However let us say that you stored your image file, some_image.jpg, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py, your route decorator looks like @blah.routes('/folder'). You then have to ask for your image file this way: {{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}

    I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.

    How to find out if an installed Eclipse is 32 or 64 bit version?

    Hit Ctrl+Alt+Del to open the Windows Task manager and switch to the processes tab.

    32-bit programs should be marked with *32.

    Converting string to double in C#

    Most people already tried to answer your questions.
    If you are still debugging, have you thought about using:

    Double.TryParse(String, Double);
    

    This will help you in determining what is wrong in each of the string first before you do the actual parsing.
    If you have a culture-related problem, you might consider using:

    Double.TryParse(String, NumberStyles, IFormatProvider, Double);
    

    This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.

    If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx

    Hope that helps.

    How do I pass a variable by reference?

    There are no variables in Python

    The key to understanding parameter passing is to stop thinking about "variables". There are names and objects in Python and together they appear like variables, but it is useful to always distinguish the three.

    1. Python has names and objects.
    2. Assignment binds a name to an object.
    3. Passing an argument into a function also binds a name (the parameter name of the function) to an object.

    That is all there is to it. Mutability is irrelevant to this question.

    Example:

    a = 1
    

    This binds the name a to an object of type integer that holds the value 1.

    b = x
    

    This binds the name b to the same object that the name x is currently bound to. Afterward, the name b has nothing to do with the name x anymore.

    See sections 3.1 and 4.2 in the Python 3 language reference.

    How to read the example in the question

    In the code shown in the question, the statement self.Change(self.variable) binds the name var (in the scope of function Change) to the object that holds the value 'Original' and the assignment var = 'Changed' (in the body of function Change) assigns that same name again: to some other object (that happens to hold a string as well but could have been something else entirely).

    How to pass by reference

    So if the thing you want to change is a mutable object, there is no problem, as everything is effectively passed by reference.

    If it is an immutable object (e.g. a bool, number, string), the way to go is to wrap it in a mutable object.
    The quick-and-dirty solution for this is a one-element list (instead of self.variable, pass [self.variable] and in the function modify var[0]).
    The more pythonic approach would be to introduce a trivial, one-attribute class. The function receives an instance of the class and manipulates the attribute.

    Oracle JDBC intermittent Connection Issue

    Just to clarify - at least from what we found on our side! It is an issue with the setup of the randomizer for Linux in the JDK distribution - and we found it in Java6, not sure about Java7. The syntax for linux for the randomizer is file:///dev/urandom, but the entry in the file is (probably left/copied from Windows) as file:/dev/urandom. So then Java probably falls back on the default, which happens to be /dev/random. And which doesn't work on a headless machine!!!

    How to find out what the date was 5 days ago?

    define('SECONDS_PER_DAY', 86400);
    $days_ago = date('Y-m-d', time() - 5 * SECONDS_PER_DAY);
    

    Other than that, you can use strtotime for any date:

    $days_ago = date('Y-m-d', strtotime('January 18, 2034') - 5 * SECONDS_PER_DAY);
    

    Or, as you used, mktime:

    $days_ago = date('Y-m-d', mktime(0, 0, 0, 12, 2, 2008) - 5 * SECONDS_PER_DAY);
    

    Well, you get it. The key is to remove enough seconds from the timestamp.

    How can I remove an element from a list, with lodash?

    In Addition to @thefourtheye answer, using predicate instead of traditional anonymous functions:

      _.remove(obj.subTopics, (currentObject) => {
            return currentObject.subTopicId === stToDelete;
        });
    

    OR

    obj.subTopics = _.filter(obj.subTopics, (currentObject) => {
        return currentObject.subTopicId !== stToDelete;
    });
    

    Filter output in logcat by tagname

    Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:

    $ adb shell logcat | grep YouTag
    # just like: 
    $ ps -ef | grep your_proc 
    

    How to get past the login page with Wget?

    I wanted a one-liner that didn't download any files; here is an example of piping the cookie output into the next request. I only tested the following on Gentoo, but it should work in most *nix environments:

    wget -q -O /dev/null --save-cookies /dev/stdout --post-data 'u=user&p=pass' 'http://example.com/login' | wget -q -O - --load-cookies /dev/stdin 'http://example.com/private/page'
    

    (This is one line, though it likely wraps on your browser)

    If you want the output saved to a file, change -O - to -O /some/file/name.ext

    Call to undefined function mysql_query() with Login

    You are mixing the deprecated mysql extension with mysqli.

    Try something like:

    $sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
    $row = mysqli_num_rows($sql);
    

    Attaching click to anchor tag in angular

    <a href="#" (click)="onGoToPage2()">Go to page 2</a>
    

    Alternative for PHP_excel

    I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

    http://github.com/elidickinson/php-export-data

    How to rotate x-axis tick labels in Pandas barplot

    The question is clear but the title is not as precise as it could be. My answer is for those who came looking to change the axis label, as opposed to the tick labels, which is what the accepted answer is about. (The title has now been corrected).

    for ax in plt.gcf().axes:
        plt.sca(ax)
        plt.xlabel(ax.get_xlabel(), rotation=90)
    

    XML to CSV Using XSLT

    Found an XML transform stylesheet here (wayback machine link, site itself is in german)

    The stylesheet added here could be helpful:

    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="iso-8859-1"/>
    
    <xsl:strip-space elements="*" />
    
    <xsl:template match="/*/child::*">
    <xsl:for-each select="child::*">
    <xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>",    </xsl:if>
    <xsl:if test="position()  = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>&#xD;</xsl:text>
    </xsl:if>
    </xsl:for-each>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.

    Resize image in PHP

    You need to use either PHP's ImageMagick or GD functions to work with images.

    With GD, for example, it's as simple as...

    function resize_image($file, $w, $h, $crop=FALSE) {
        list($width, $height) = getimagesize($file);
        $r = $width / $height;
        if ($crop) {
            if ($width > $height) {
                $width = ceil($width-($width*abs($r-$w/$h)));
            } else {
                $height = ceil($height-($height*abs($r-$w/$h)));
            }
            $newwidth = $w;
            $newheight = $h;
        } else {
            if ($w/$h > $r) {
                $newwidth = $h*$r;
                $newheight = $h;
            } else {
                $newheight = $w/$r;
                $newwidth = $w;
            }
        }
        $src = imagecreatefromjpeg($file);
        $dst = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
        return $dst;
    }
    

    And you could call this function, like so...

    $img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
    

    From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.

    Reversing an Array in Java

    This code would help:

    int [] a={1,2,3,4,5,6,7};
    for(int i=a.length-1;i>=0;i--)
      System.out.println(a[i]);
    

    SQL Server String Concatenation with Null

    I had a lot of trouble with this too. Couldn't get it working using the case examples above, but this does the job for me:

    Replace(rtrim(ltrim(ISNULL(Flat_no, '') + 
    ' ' + ISNULL(House_no, '') + 
    ' ' + ISNULL(Street, '') + 
    ' ' + ISNULL(Town, '') + 
    ' ' + ISNULL(City, ''))),'  ',' ')
    

    Replace corrects the double spaces caused by concatenating single spaces with nothing between them. r/ltrim gets rid of any spaces at the ends.

    Flutter - Wrap text on overflow, like insert ellipsis or fade

    There are many answers but Will some more observation it.

    1. clip

    Clip the overflowing text to fix its container.

    SizedBox(
              width: 120.0,
              child: Text(
                "Enter Long Text",
                maxLines: 1,
                overflow: TextOverflow.clip,
                softWrap: false,
                style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
              ),
            ),
    

    Output:

    enter image description here

    2.fade

    Fade the overflowing text to transparent.

    SizedBox(
              width: 120.0,
              child: Text(
                "Enter Long Text",
                maxLines: 1,
                overflow: TextOverflow.fade,
                softWrap: false,
                style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
              ),
            ), 
    

    Output:

    enter image description here

    3.ellipsis

    Use an ellipsis to indicate that the text has overflowed.

    SizedBox(
              width: 120.0,
              child: Text(
                "Enter Long Text",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                softWrap: false,
                style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
              ),
            ),
    

    Output:

    enter image description here

    4.visible

    Render overflowing text outside of its container.

    SizedBox(
              width: 120.0,
              child: Text(
                "Enter Long Text",
                maxLines: 1,
                overflow: TextOverflow.visible,
                softWrap: false,
                style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0),
              ),
            ),
    

    Output:

    enter image description here

    Please Blog: https://medium.com/flutterworld/flutter-text-wrapping-ellipsis-4fa70b19d316

    Check if a string is a valid Windows directory (folder) path

        private bool IsValidPath(string path)
        {
            Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
            if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
            string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
            strTheseAreInvalidFileNameChars += @":/?*" + "\"";
            Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
            if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
                return false;
    
            DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
            if (!dir.Exists)
                dir.Create();
            return true;
        }
    

    Print content of JavaScript object?

    You can give your objects their own toString methods in their prototypes.

    iText - add content to existing PDF file

    This is the most complicated scenario I can imagine: I have a PDF file created with Ilustrator and modified with Acrobat to have AcroFields (AcroForm) that I'm going to fill with data with this Java code, the result of that PDF file with the data in the fields is modified adding a Document.

    Actually in this case I'm dynamically generating a background that is added to a PDF that is also dynamically generated with a Document with an unknown amount of data or pages.

    I'm using JBoss and this code is inside a JSP file (should work in any JSP webserver).

    Note: if you are using IExplorer you must submit a HTTP form with POST method to be able to download the file. If not you are going to see the PDF code in the screen. This does not happen in Chrome or Firefox.

    <%@ page import="java.io.*, com.lowagie.text.*, com.lowagie.text.pdf.*" %><%
    
    response.setContentType("application/download");
    response.setHeader("Content-disposition","attachment;filename=listaPrecios.pdf" );  
    
    // -------- FIRST THE PDF WITH THE INFO ----------
    String str = "";
    // lots of words
    for(int i = 0; i < 800; i++) str += "Hello" + i + " ";
    // the document
    Document doc = new Document( PageSize.A4, 25, 25, 200, 70 );
    ByteArrayOutputStream streamDoc = new ByteArrayOutputStream();
    PdfWriter.getInstance( doc, streamDoc );
    // lets start filling with info
    doc.open();
    doc.add(new Paragraph(str));
    doc.close();
    // the beauty of this is the PDF will have all the pages it needs
    PdfReader frente = new PdfReader(streamDoc.toByteArray());
    PdfStamper stamperDoc = new PdfStamper( frente, response.getOutputStream());
    
    // -------- THE BACKGROUND PDF FILE -------
    // in JBoss the file has to be in webinf/classes to be readed this way
    PdfReader fondo = new PdfReader("listaPrecios.pdf");
    ByteArrayOutputStream streamFondo = new ByteArrayOutputStream();
    PdfStamper stamperFondo = new PdfStamper( fondo, streamFondo);
    // the acroform
    AcroFields form = stamperFondo.getAcroFields();
    // the fields 
    form.setField("nombre","Avicultura");
    form.setField("descripcion","Esto describe para que sirve la lista ");
    stamperFondo.setFormFlattening(true);
    stamperFondo.close();
    // our background is ready
    PdfReader fondoEstampado = new PdfReader( streamFondo.toByteArray() );
    
    // ---- ADDING THE BACKGROUND TO EACH DATA PAGE ---------
    PdfImportedPage pagina = stamperDoc.getImportedPage(fondoEstampado,1);
    int n = frente.getNumberOfPages();
    PdfContentByte background;
    for (int i = 1; i <= n; i++) {
        background = stamperDoc.getUnderContent(i);
        background.addTemplate(pagina, 0, 0);
    }
    // after this everithing will be written in response.getOutputStream()
    stamperDoc.close(); 
    %>
    

    There is another solution much simpler, and solves your problem. It depends the amount of text you want to add.

    // read the file
    PdfReader fondo = new PdfReader("listaPrecios.pdf");
    PdfStamper stamper = new PdfStamper( fondo, response.getOutputStream());
    PdfContentByte content = stamper.getOverContent(1);
    // add text
    ColumnText ct = new ColumnText( content );
    // this are the coordinates where you want to add text
    // if the text does not fit inside it will be cropped
    ct.setSimpleColumn(50,500,500,50);
    ct.setText(new Phrase(str, titulo1));
    ct.go();
    

    java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

    To be more specific if you are missing the class com.vaadin.external.org.slf4j.LoggerFactory add the below dependency.

    <dependency>
        <groupId>com.vaadin.external.slf4j</groupId>
        <artifactId>vaadin-slf4j-jdk14</artifactId>
        <version>1.6.1</version>
    </dependency>
    

    If you are missing any other org.slf4j.LoggerFactory, just go to Maven central class name search and search for the exact class name to determine what exact dependency you are missing.

    How to automatically generate unique id in SQL like UID12345678?

    CREATE TABLE dbo.tblUsers
    (
        ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
        UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED, 
        [Name] VARCHAR(50) NOT NULL,
    )
    

    marc_s's Answer Snap

    marc_s's Answer Snap

    Check if an array is empty or exists

    To check if an array is either empty or not

    A modern way, ES5+:

    if (Array.isArray(array) && array.length) {
        // array exists and is not empty
    }
    

    An old-school way:

    typeof array != "undefined"
        && array != null
        && array.length != null
        && array.length > 0
    

    A compact way:

    if (typeof array != "undefined" && array != null && array.length != null && array.length > 0) {
        // array exists and is not empty
    }
    

    A CoffeeScript way:

    if array?.length > 0
    

    Why?

    Case Undefined
    Undefined variable is a variable that you haven't assigned anything to it yet.

    let array = new Array();     // "array" !== "array"
    typeof array == "undefined"; // => true
    

    Case Null
    Generally speaking, null is state of lacking a value. For example a variable is null when you missed or failed to retrieve some data.

    array = searchData();  // can't find anything
    array == null;         // => true
    

    Case Not an Array
    Javascript has a dynamic type system. This means we can't guarantee what type of object a variable holds. There is a chance that we're not talking to an instance of Array.

    supposedToBeArray =  new SomeObject();
    typeof supposedToBeArray.length;       // => "undefined"
    
    array = new Array();
    typeof array.length;                   // => "number"
    

    Case Empty Array
    Now since we tested all other possibilities, we're talking to an instance of Array. In order to make sure it's not empty, we ask about number of elements it's holding, and making sure it has more than zero elements.

    firstArray = [];
    firstArray.length > 0;  // => false
    
    secondArray = [1,2,3];
    secondArray.length > 0; // => true
    

    Serializing/deserializing with memory stream

    This code works for me:

    public void Run()
    {
        Dog myDog = new Dog();
        myDog.Name= "Foo";
        myDog.Color = DogColor.Brown;
    
        System.Console.WriteLine("{0}", myDog.ToString());
    
        MemoryStream stream = SerializeToStream(myDog);
    
        Dog newDog = (Dog)DeserializeFromStream(stream);
    
        System.Console.WriteLine("{0}", newDog.ToString());
    }
    

    Where the types are like this:

    [Serializable]
    public enum DogColor
    {
        Brown,
        Black,
        Mottled
    }
    
    [Serializable]
    public class Dog
    {
        public String Name
        {
            get; set;
        }
    
        public DogColor Color
        {
            get;set;
        }
    
        public override String ToString()
        {
            return String.Format("Dog: {0}/{1}", Name, Color);
        }
    }
    

    and the utility methods are:

    public static MemoryStream SerializeToStream(object o)
    {
        MemoryStream stream = new MemoryStream();
        IFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, o);
        return stream;
    }
    
    public static object DeserializeFromStream(MemoryStream stream)
    {
        IFormatter formatter = new BinaryFormatter();
        stream.Seek(0, SeekOrigin.Begin);
        object o = formatter.Deserialize(stream);
        return o;
    }
    

    Convert Existing Eclipse Project to Maven Project

    Start from m2e 0.13.0 (if not earlier than), you can convert a Java project to Maven project from the context menu. Here is how:

    • Right click the Java project to pop up the context menu
    • Select Configure > Convert to Maven Project

    Here is the detailed steps with screen shots.

    JavaScript hard refresh of current page

    Try to use:

    location.reload(true);
    

    When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

    More info:

    Add SUM of values of two LISTS into new LIST

    You can use zip(), which will "interleave" the two arrays together, and then map(), which will apply a function to each element in an iterable:

    >>> a = [1,2,3,4,5]
    >>> b = [6,7,8,9,10]
    >>> zip(a, b)
    [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
    >>> map(lambda x: x[0] + x[1], zip(a, b))
    [7, 9, 11, 13, 15]
    

    Can HTML be embedded inside PHP "if" statement?

    I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.

    In the php

    <?php 
      $var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';
    
      if ($var1 == 'Alice') {
        $html = file_get_contents('/path/to/file.html'); //get the html template
        $template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
        $template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
        $html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
      }
    
      echo $html_output;
    ?>
    

    In the html (/path/to/file.html)

    <p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>
    

    The output of this would be:

    Alice ate apples for lunch with Bob.
    

    Update query using Subquery in Sql Server

    because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:

    SELECT *
    FROM    tempDataView a
            INNER JOIN tempData b
                ON a.Name = b.Name
    

    Then note that we have two table aliases a and b. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b, the statement will be:

    UPDATE  b
    SET     b.marks = a.marks
    FROM    tempDataView a
            INNER JOIN tempData b
                ON a.Name = b.Name
    

    Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a only (leaving b intact) for those records that match by name:

    DELETE a
    FROM    tempDataView a
            INNER JOIN tempData b
                ON a.Name = b.Name
    

    You can use the SQL Fiddle created by JW as a playground

    Angular 2 Hover event

    yes there is on-mouseover in angular2 instead of ng-Mouseover like in angular 1.x so you have to write this :-

    <div on-mouseover='over()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>
    
    over(){
        console.log("Mouseover called");
      }
    

    As @Gunter Suggested in comment there is alternate of on-mouseover we can use this too. Some people prefer the on- prefix alternative, known as the canonical form.

    Update

    HTML Code -

    <div (mouseover)='over()' (mouseout)='out()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>
    

    Controller/.TS Code -

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular';
    
      over(){
        console.log("Mouseover called");
      }
    
      out(){
        console.log("Mouseout called");
      }
    }
    

    Working Example

    Some other Mouse events can be used in Angular -

    (mouseenter)="myMethod()"
    (mousedown)="myMethod()"
    (mouseup)="myMethod()"
    

    what is the difference between XSD and WSDL

    XSD (XML schema definition) defines the element in an XML document. It can be used to verify if the elements in the xml document adheres to the description in which the content is to be placed. While wsdl is specific type of XML document which describes the web service. WSDL itself adheres to a XSD.

    HTML form do some "action" when hit submit button

    index.html

    <!DOCTYPE html>
    <html>
       <body>
           <form action="submit.php" method="POST">
             First name: <input type="text" name="firstname" /><br /><br />
             Last name: <input type="text" name="lastname" /><br />
             <input type="submit" value="Submit" />
          </form> 
       </body>
    </html>
    

    After that one more file which page you want to display after pressing the submit button

    submit.php

    <html>
      <body>
    
        Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
        Your Last Name is -   <?php echo $_POST["lastname"]; ?>
    
      </body>
    </html>
    

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

    You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

    See Python json.loads shows ValueError: Extra data

    OR you need to reformat your json to contain an array:

    {
        "foo" : [
           {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
           {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
        ]
    }
    

    would be acceptable again. But there cannot be several top level objects.

    Get $_POST from multiple checkboxes

    <input type="checkbox" name="check_list[<? echo $row['Report ID'] ?>]" value="<? echo $row['Report ID'] ?>">
    

    And after the post, you can loop through them:

       if(!empty($_POST['check_list'])){
         foreach($_POST['check_list'] as $report_id){
            echo "$report_id was checked! ";
         }
       }
    

    Or get a certain value posted from previous page:

    if(isset($_POST['check_list'][$report_id])){
      echo $report_id . " was checked!<br/>";
    }
    

    Does a TCP socket connection have a "keep alive"?

    You are looking for the SO_KEEPALIVE socket option.

    The Java Socket API exposes "keep-alive" to applications via the setKeepAlive and getKeepAlive methods.

    EDIT: SO_KEEPALIVE is implemented in the OS network protocol stacks without sending any "real" data. The keep-alive interval is operating system dependent, and may be tuneable via a kernel parameter.

    Since no data is sent, SO_KEEPALIVE can only test the liveness of the network connection, not the liveness of the service that the socket is connected to. To test the latter, you need to implement something that involves sending messages to the server and getting a response.

    Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

    Check the site's Application Pool in IIS / Application Pools / YourPool / Advanced Settings :

    • Advanced / Enable 32-Bit Applications: True

    There's some anecdotal evidence to suggest you do this too:

    • Managed Pipeline Mode : Classic

    XPath to select multiple tags

    Why not a/b/(c|d|e)? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work. abc.xml is the doc described by OP.

    (require '[saxon :as xml])
    (def abc-doc (xml/compile-xml (slurp "abc.xml")))
    (xml/query "a/b/(c|d|e)" abc-doc)
    => (#<XdmNode <c>C1</c>>
        #<XdmNode <d>D1</d>>
        #<XdmNode <e>E1</e>>
        #<XdmNode <c>C2</c>>
        #<XdmNode <d>D2</d>>
        #<XdmNode <e>E1</e>>)
    

    How to redirect Valgrind's output to a file?

    valgrind --log-file="filename"
    

    Inserting HTML into a div

    I think this is what you want:

    document.getElementById('tag-id').innerHTML = '<ol><li>html data</li></ol>';
    

    Keep in mind that innerHTML is not accessible for all types of tags when using IE. (table elements for example)

    Docker - a way to give access to a host USB or serial device?

    Adding to the answers above, for those who want a quick way to use an external USB device (HDD, flash drive) working inside docker, and not using priviledged mode:

    Find the devpath to your device on the host:

    sudo fdisk -l
    

    You can recognize your drive by it's capacity quite easily from the list. Copy this path (for the following example it is /dev/sda2).

    Disque /dev/sda2 : 554,5 Go, 57151488 octets, 111624 secteurs
    Unités : secteur de 1 × 512 = 512 octets
    Taille de secteur (logique / physique) : 512 octets / 512 octets
    taille d'E/S (minimale / optimale) : 512 octets / 512 octets
    

    Mount this devpath (preferable to /media):

    sudo mount <drive path> /media/<mount folder name>
    

    You can then use this either as a param to docker run like:

    docker run -it -v /media/<mount folder name>:/media/<mount folder name>
    

    or in docker compose under volumes:

    services:
      whatevermyserviceis:
        volumes:
          - /media/<mount folder name>:/media/<mount folder name>
    

    And now when you run and enter your container, you should be able to access the drive inside the container at /media/<mount folder name>

    DISCLAIMER:

    1. This will probably not work for serial devices such as webcams etc. I have only tested this for USB storage drives.
    2. If you need to reconnect and disconnect devices regularly, this method would be annoying, and also would not work unless you reset the mount path and restart the container.
    3. I used docker 17.06 + as prescribed in the docs

    How to enable local network users to access my WAMP sites?

    go to... 
    C:\wamp\alias
    

    Inside alias folder you will see some files like phpmyadmin,phpsysinfo,etc...

    open each file, and you can see inside file some commented instruction are give to access from outside ,like to give access to phpmyadmin from outside replace the lines

    Require local
    
    by
    
    Require all granted
    

    Excel date to Unix timestamp

    Here's my ultimate answer to this.

    Also apparently javascript's new Date(year, month, day) constructor doesn't account for leap seconds too.

    // Parses an Excel Date ("serial") into a
    // corresponding javascript Date in UTC+0 timezone.
    //
    // Doesn't account for leap seconds.
    // Therefore is not 100% correct.
    // But will do, I guess, since we're
    // not doing rocket science here.
    //
    // https://www.pcworld.com/article/3063622/software/mastering-excel-date-time-serial-numbers-networkdays-datevalue-and-more.html
    // "If you need to calculate dates in your spreadsheets,
    //  Excel uses its own unique system, which it calls Serial Numbers".
    //
    lib.parseExcelDate = function (excelSerialDate) {
      // "Excel serial date" is just
      // the count of days since `01/01/1900`
      // (seems that it may be even fractional).
      //
      // The count of days elapsed
      // since `01/01/1900` (Excel epoch)
      // till `01/01/1970` (Unix epoch).
      // Accounts for leap years
      // (19 of them, yielding 19 extra days).
      const daysBeforeUnixEpoch = 70 * 365 + 19;
    
      // An hour, approximately, because a minute
      // may be longer than 60 seconds, see "leap seconds".
      const hour = 60 * 60 * 1000;
    
      // "In the 1900 system, the serial number 1 represents January 1, 1900, 12:00:00 a.m.
      //  while the number 0 represents the fictitious date January 0, 1900".
      // These extra 12 hours are a hack to make things
      // a little bit less weird when rendering parsed dates.
      // E.g. if a date `Jan 1st, 2017` gets parsed as
      // `Jan 1st, 2017, 00:00 UTC` then when displayed in the US
      // it would show up as `Dec 31st, 2016, 19:00 UTC-05` (Austin, Texas).
      // That would be weird for a website user.
      // Therefore this extra 12-hour padding is added
      // to compensate for the most weird cases like this
      // (doesn't solve all of them, but most of them).
      // And if you ask what about -12/+12 border then
      // the answer is people there are already accustomed
      // to the weird time behaviour when their neighbours
      // may have completely different date than they do.
      //
      // `Math.round()` rounds all time fractions
      // smaller than a millisecond (e.g. nanoseconds)
      // but it's unlikely that an Excel serial date
      // is gonna contain even seconds.
      //
      return new Date(Math.round((excelSerialDate - daysBeforeUnixEpoch) * 24 * hour) + 12 * hour);
    };
    

    Missing Push Notification Entitlement

    check Your App Id is Push Enabled or not on developer.apple.com in iOS Provisioning Portal If Not then Enabled it,configure Your Push SSL Certificate for your App Id Download it, and Reinstall in Your Keychain Once again then Download Your Distrubution Profile install in your Xcode Liabrary

    Removing leading and trailing spaces from a string

    void removeSpaces(string& str)
    {
        /* remove multiple spaces */
        int k=0;
        for (int j=0; j<str.size(); ++j)
        {
                if ( (str[j] != ' ') || (str[j] == ' ' && str[j+1] != ' ' ))
                {
                        str [k] = str [j];
                        ++k;
                }
    
        }
        str.resize(k);
    
        /* remove space at the end */   
        if (str [k-1] == ' ')
                str.erase(str.end()-1);
        /* remove space at the begin */
        if (str [0] == ' ')
                str.erase(str.begin());
    }
    

    What is the syntax for adding an element to a scala.collection.mutable.Map?

    When you say

    val map = scala.collection.mutable.Map
    

    you are not creating a map instance, but instead aliasing the Map type.

    map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e
    

    Try instead the following:

    scala> val map = scala.collection.mutable.Map[String, Int]()
    map: scala.collection.mutable.Map[String,Int] = Map()
    
    scala> map("asdf") = 9
    
    scala> map
    res6: scala.collection.mutable.Map[String,Int] = Map((asdf,9))
    

    How to give spacing between buttons using bootstrap

    Use btn-primary-spacing class for all buttons remove margin-left class

    Example :

    <button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2 btn-primary-spacing">
      <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> ADD PACKET
    </button>
    

    CSS will be like :

    .btn-primary-spacing 
    {
    margin-right: 5px;
    margin-bottom: 5px !important;
    }
    

    Sorting rows in a data table

    Or, if you can use a DataGridView, you could just call Sort(column, direction):

    namespace Sorter
    {
        using System;
        using System.ComponentModel;
        using System.Windows.Forms;
    
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                this.dataGridView1.Rows.Add("Abc", 5);
                this.dataGridView1.Rows.Add("Def", 8);
                this.dataGridView1.Rows.Add("Ghi", 3);
                this.dataGridView1.Sort(this.dataGridView1.Columns[1], 
                                        ListSortDirection.Ascending);
            }
        }
    }
    

    Which would give you the desired result:

    Debugger view

    Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

    I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

    @Bean
    public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
        final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));
    
        // Add some specific configuration here. Key serializers, etc.
        return template;
    }
    

    The fix was to specify an array of RoutePlantCache as following:

    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));
    

    Below the exception I had:

    com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
     at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
        at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
        at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
        at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
        at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
        at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
        at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
        at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]
    

    How do I install cURL on cygwin?

    apt-cyg is a great installer similar to apt-get to easily install any packages for Cygwin.

    $ apt-cyg install curl
    

    Note: apt-cyg should be first installed. You can do this from Windows command line:

    cd c:\cygwin
    cygwinsetup.exe -q -P wget,tar,qawk, bzip2,vim,lynx
    

    Close Windows cmd, and open Cygwin Bash.

    $ lynx -source rawgit.com/transcode-open/apt-cyg/master/apt-cyg > apt-cyg install apt-cyg /bin
    $ chmod +x /bin/apt-cyg
    

    Apache: The requested URL / was not found on this server. Apache

    Non-trivial reasons:

    • if your .htaccess is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert )
    • if your .htaccess is in UTF8 Without-BOM, make it WITH BOM.

    HTTP Headers for File Downloads

    Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

    The recommended action for an implementation that receives an
    "application/octet-stream" entity is to simply offer to put the data in a file

    So I'd go for that one.

    What are the advantages of NumPy over regular Python lists?

    Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.

    Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?

    Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).

    from numpy import arange
    from timeit import Timer
    
    Nelements = 10000
    Ntimeits = 10000
    
    x = arange(Nelements)
    y = range(Nelements)
    
    t_numpy = Timer("x.sum()", "from __main__ import x")
    t_list = Timer("sum(y)", "from __main__ import y")
    print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
    print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))
    

    which on my systems (while I'm running a backup) gives:

    numpy: 3.004e-05
    list:  5.363e-04
    

    ImportError: No module named PyQt4

    You have to check which Python you are using. I had the same problem because the Python I was using was not the same one that brew was using. In your command line:

    1. which python
      output: /usr/bin/python
    2. which brew
      output: /usr/local/bin/brew     //so they are different
    3. cd /usr/local/lib/python2.7/site-packages
    4. ls   //you can see PyQt4 and sip are here
    5. Now you need to add usr/local/lib/python2.7/site-packages to your python path.
    6. open ~/.bash_profile   //you will open your bash_profile file in your editor
    7. Add 'export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH' to your bash file and save it
    8. Close your terminal and restart it to reload the shell
    9. python
    10. import PyQt4    // it is ok now

    HTML - how can I show tooltip ONLY when ellipsis is activated

    Here's a Vanilla JavaScript solution:

    _x000D_
    _x000D_
    (function init() {_x000D_
    _x000D_
      var cells = document.getElementsByClassName("cell");_x000D_
    _x000D_
      for(let index = 0; index < cells.length; ++index) {_x000D_
        let cell = cells.item(index);_x000D_
        cell.addEventListener('mouseenter', setTitleIfNecessary, false);_x000D_
      }_x000D_
    _x000D_
      function setTitleIfNecessary() {_x000D_
        if(this.offsetWidth < this.scrollWidth) {_x000D_
          this.setAttribute('title', this.innerHTML);_x000D_
        }_x000D_
      }_x000D_
    _x000D_
    })();
    _x000D_
    .cell {_x000D_
      white-space: nowrap;_x000D_
      overflow: hidden;_x000D_
      text-overflow: ellipsis;_x000D_
      border: 1px;_x000D_
      border-style: solid;_x000D_
      width: 120px; _x000D_
    }
    _x000D_
    <div class="cell">hello world!</div>_x000D_
    <div class="cell">hello mars! kind regards, world</div>
    _x000D_
    _x000D_
    _x000D_

    val() doesn't trigger change() in jQuery

    You need to chain the method like this:

    $('#input').val('test').change();
    

    How to pass table value parameters to stored procedure from .net code

    Further to Ryan's answer you will also need to set the DataColumn's Ordinal property if you are dealing with a table-valued parameter with multiple columns whose ordinals are not in alphabetical order.

    As an example, if you have the following table value that is used as a parameter in SQL:

    CREATE TYPE NodeFilter AS TABLE (
      ID int not null
      Code nvarchar(10) not null,
    );
    

    You would need to order your columns as such in C#:

    table.Columns["ID"].SetOrdinal(0);
    // this also bumps Code to ordinal of 1
    // if you have more than 2 cols then you would need to set more ordinals
    

    If you fail to do this you will get a parse error, failed to convert nvarchar to int.

    Batch File: ( was unexpected at this time

    you need double quotes in all your three if statements, eg.:

    IF "%a%"=="2" (
    

    @echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
    cls
    title ~USB Wizard~
    echo What do you want to do?
    echo 1.Enable/Disable USB Storage Devices.
    echo 2.Enable/Disable Writing Data onto USB Storage.
    echo 3.~Yet to come~.
    
    
    set "a=%globalparam1%"
    goto :aCheck
    :aPrompt
    set /p "a=Enter Choice: "
    :aCheck
    if "%a%"=="" goto :aPrompt
    echo %a%
    
    IF "%a%"=="2" (
        title USB WRITE LOCK
        echo What do you want to do?
        echo 1.Apply USB Write Protection
        echo 2.Remove USB Write Protection
        ::param1
        set "param1=%globalparam2%"
        goto :param1Check
        :param1Prompt
        set /p "param1=Enter Choice: "
        :param1Check
        if "!param1!"=="" goto :param1Prompt
    
        if "!param1!"=="1" (
             REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
             USB Write is Locked!
        )
        if "!param1!"=="2" (
             REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
             USB Write is Unlocked!
        )
    )
    pause
    

    How to determine if one array contains all elements of another array

    a = [5, 1, 6, 14, 2, 8]
    b = [2, 6, 15]
    
    a - b
    # => [5, 1, 14, 8]
    
    b - a
    # => [15]
    
    (b - a).empty?
    # => false
    

    Remote Linux server to remote linux server dir copy. How?

    Use rsync so that you can continue if the connection gets broken. And if something changes you can copy them much faster too!

    Rsync works with SSH so your copy operation is secure.

    Is there an upside down caret character?

    Could you just draw an svg path inside of a span using document.write? The span isn't required for the svg to work, it just ensures that the svg remains inline with whatever text the carat is next to. I used margin-bottom to vertically center it with the text, there might be another way to do that though. This is what I did on my blog's side nav (minus the js). If you don't have text next to it you wouldn't need the span or the margin-bottom offset.

    <div id="ID"></div>
    
    <script type="text/javascript">
    var x = document.getElementById('ID');
    
    // your "margin-bottom" is the negative of 1/2 of the font size (in this example the font size is 16px)
    // change the "stroke=" to whatever color your font is too
    x.innerHTML = document.write = '<span><svg style="margin-bottom: -8px; height: 30px; width: 25px;" viewBox="0,0,100,50"><path fill="transparent" stroke-width="4" stroke="black" d="M20 10 L50 40 L80 10"/></svg></span>';
    </script>
    

    Adding a new entry to the PATH variable in ZSH

    You can append to your PATH in a minimal fashion. No need for parentheses unless you're appending more than one element. It also usually doesn't need quotes. So the simple, short way to append is:

    path+=/some/new/bin/dir
    

    This lower-case syntax is using path as an array, yet also affects its upper-case partner equivalent, PATH (to which it is "bound" via typeset).

    (Notice that no : is needed/wanted as a separator.)

    Common interactive usage

    Then the common pattern for testing a new script/executable becomes:

    path+=$PWD/.
    # or
    path+=$PWD/bin
    

    Common config usage

    You can sprinkle path settings around your .zshrc (as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)).

    Related tidbits

    Treating path this way (as an array) also means: no need to do a rehash to get the newly pathed commands to be found.

    Also take a look at vared path as a dynamic way to edit path (and other things).

    You may only be interested in path for this question, but since we're talking about exports and arrays, note that arrays generally cannot be exported.

    You can even prevent PATH from taking on duplicate entries (refer to this and this):

    typeset -U path
    

    How to block calls in android

    You could just re-direct specific numbers in your contacts to your voice-mail. That's already supported.

    Otherwise I guess the documentation for 'Contacts' would be a good place to start looking.

    ReferenceError: describe is not defined NodeJs

    You can also do like this:

      var mocha = require('mocha')
      var describe = mocha.describe
      var it = mocha.it
      var assert = require('chai').assert
    
      describe('#indexOf()', function() {
        it('should return -1 when not present', function() {
          assert.equal([1,2,3].indexOf(4), -1)
        })
      })
    

    Reference: http://mochajs.org/#require

    How to implement class constants?

    Constants can be declare outside of classes and use within your class. Otherwise the get property is a nice workaround

    const MY_CONSTANT: string = "wazzup";
    
    export class MyClass {
    
        public myFunction() {
    
            alert(MY_CONSTANT);
        }
    }
    

    Changing an AIX password via script?

    Just this

    passwd <<EOF
    oldpassword
    newpassword
    newpassword
    EOF
    

    Actual output from ubuntu machine (sorry no AIX available to me):

    user@host:~$ passwd <<EOF
    oldpassword
    newpassword
    newpassword
    EOF
    
    Changing password for user.
    (current) UNIX password: Enter new UNIX password: Retype new UNIX password: 
    passwd: password updated successfully
    user@host:~$
    

    How to part DATE and TIME from DATETIME in MySQL

    Try:

    SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`
    

    api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

    While the answer from alireza is correct, it has one gotcha:

    You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).

    How to compare strings in C conditional preprocessor-directives

    You can't do that if USER is defined as a quoted string.

    But you can do that if USER is just JACK or QUEEN or Joker or whatever.

    There are two tricks to use:

    1. Token-splicing, where you combine an identifier with another identifier by just concatenating their characters. This allows you to compare against JACK without having to #define JACK to something
    2. variadic macro expansion, which allows you to handle macros with variable numbers of arguments. This allows you to expand specific identifiers into varying numbers of commas, which will become your string comparison.

    So let's start out with:

    #define JACK_QUEEN_OTHER(u) EXPANSION1(ReSeRvEd_, u, 1, 2, 3)
    

    Now, if I write JACK_QUEEN_OTHER(USER), and USER is JACK, the preprocessor turns that into EXPANSION1(ReSeRvEd_, JACK, 1, 2, 3)

    Step two is concatenation:

    #define EXPANSION1(a, b, c, d, e) EXPANSION2(a##b, c, d, e)
    

    Now JACK_QUEEN_OTHER(USER) becomes EXPANSION2(ReSeRvEd_JACK, 1, 2, 3)

    This gives the opportunity to add a number of commas according to whether or not a string matches:

    #define ReSeRvEd_JACK x,x,x
    #define ReSeRvEd_QUEEN x,x
    

    If USER is JACK, JACK_QUEEN_OTHER(USER) becomes EXPANSION2(x,x,x, 1, 2, 3)

    If USER is QUEEN, JACK_QUEEN_OTHER(USER) becomes EXPANSION2(x,x, 1, 2, 3)

    If USER is other, JACK_QUEEN_OTHER(USER) becomes EXPANSION2(ReSeRvEd_other, 1, 2, 3)

    At this point, something critical has happened: the fourth argument to the EXPANSION2 macro is either 1, 2, or 3, depending on whether the original argument passed was jack, queen, or anything else. So all we have to do is pick it out. For long-winded reasons, we'll need two macros for the last step; they'll be EXPANSION2 and EXPANSION3, even though one seems unnecessary.

    Putting it all together, we have these 6 macros:

    #define JACK_QUEEN_OTHER(u) EXPANSION1(ReSeRvEd_, u, 1, 2, 3)
    #define EXPANSION1(a, b, c, d, e) EXPANSION2(a##b, c, d, e)
    #define EXPANSION2(a, b, c, d, ...) EXPANSION3(a, b, c, d)
    #define EXPANSION3(a, b, c, d, ...) d
    #define ReSeRvEd_JACK x,x,x
    #define ReSeRvEd_QUEEN x,x
    

    And you might use them like this:

    int main() {
    #if JACK_QUEEN_OTHER(USER) == 1
      printf("Hello, Jack!\n");
    #endif
    #if JACK_QUEEN_OTHER(USER) == 2
      printf("Hello, Queen!\n");
    #endif
    #if JACK_QUEEN_OTHER(USER) == 3
      printf("Hello, who are you?\n");
    #endif
    }
    

    Obligatory godbolt link: https://godbolt.org/z/8WGa19


    MSVC Update: You have to parenthesize slightly differently to make things also work in MSVC. The EXPANSION* macros look like this:

    #define EXPANSION1(a, b, c, d, e) EXPANSION2((a##b, c, d, e))
    #define EXPANSION2(x) EXPANSION3 x
    #define EXPANSION3(a, b, c, d, ...) d
    

    Obligatory: https://godbolt.org/z/96Y8a1

    jquery disable form submit on enter

    How about this:

    $(":submit").closest("form").submit(function(){
        $(':submit').attr('disabled', 'disabled');
    });
    

    This should disable all forms with submit buttons in your app.

    How to write dynamic variable in Ansible playbook

    my_var: the variable declared

    VAR: the variable, whose value is to be checked

    param_1, param_2: values of the variable VAR

    value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var

    my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"
    

    Java int to String - Integer.toString(i) vs new Integer(i).toString()

    Although I like fhucho's recommendation of

    String.valueOf(i)
    

    The irony is that this method actually calls

    Integer.toString(i)
    

    Thus, use String.valueOf(i) if you like how it reads and you don't need radix, but also knowing that it is less efficient than Integer.toString(i).

    flutter corner radius with transparent background

    Use transparent background color for the modalbottomsheet and give separate color for box decoration


       showModalBottomSheet(
          backgroundColor: Colors.transparent,
          context: context, builder: (context) {
        return Container(
    
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft:Radius.circular(40) ,
                topRight: Radius.circular(40)
            ),
          ),
          padding: EdgeInsets.symmetric(vertical: 20,horizontal: 60),
          child: Settings_Form(),
        );
      });
    

    What's "this" in JavaScript onclick?

    The value of event handler attributes such as onclick should just be JavaScript, without any "javascript:" prefix. The javascript: pseudo-protocol is used in a URL, for example:

    <a href="javascript:func(this)">here</a>
    

    You should use the onclick="func(this)" form in preference to this though. Also note that in my example above using the javascript: pseudo-protocol "this" will refer to the window object rather than the <a> element.

    How does the @property decorator work in Python?

    A property can be declared in two ways.

    • Creating the getter, setter methods for an attribute and then passing these as argument to property function
    • Using the @property decorator.

    You can have a look at few examples I have written about properties in python.

    Spring boot - Not a managed type

    I am using spring boot 2.0 and I fixed this by replacing @ComponentScan with @EntityScan

    Set up adb on Mac OS X

    If you are setting the path in Catalina use below command one after another in the terminal. It's working fine for me.

    export ANDROID_HOME=/Users/$USER/Library/Android/sdk
    export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
    
    source ~/.bash_profile
    

    How can I count occurrences with groupBy?

    Here is the simple solution by StreamEx:

    StreamEx.of(list).groupingBy(Function.identity(), MoreCollectors.countingInt());
    

    This has the advantage of reducing the Java stream boilerplate code: collect(Collectors.

    What is the difference between Document style and RPC style communication?

    In WSDL definition, bindings contain operations, here comes style for each operation.

    Document : In WSDL file, it specifies types details either having inline Or imports XSD document, which describes the structure(i.e. schema) of the complex data types being exchanged by those service methods which makes loosely coupled. Document style is default.

    • Advantage:
      • Using this Document style, we can validate SOAP messages against predefined schema. It supports xml datatypes and patterns.
      • loosely coupled.
    • Disadvantage: It is a little bit hard to get understand.

    In WSDL types element looks as follows:

    <types>
     <xsd:schema>
      <xsd:import schemaLocation="http://localhost:9999/ws/hello?xsd=1" namespace="http://ws.peter.com/"/>
     </xsd:schema>
    </types>
    

    The schema is importing from external reference.

    RPC :In WSDL file, it does not creates types schema, within message elements it defines name and type attributes which makes tightly coupled.

    <types/>  
    <message name="getHelloWorldAsString">  
    <part name="arg0" type="xsd:string"/>  
    </message>  
    <message name="getHelloWorldAsStringResponse">  
    <part name="return" type="xsd:string"/>  
    </message>  
    
    • Advantage: Easy to understand.
    • Disadvantage:
      • we can not validate SOAP messages.
      • tightly coupled

    RPC : No types in WSDL
    Document: Types section would be available in WSDL

    Eclipse DDMS error "Can't bind to local 8600 for debugger"

    In addition to adding 127.0.0.1 localhost to your hosts file, make the following changes in Eclipse.

    Under

    Window -> Preferences -> Android -> DDMS

    Set Base local debugger port to 8601

    Check the box that says Use ADBHOST and the value should be 127.0.0.1 Thanks to Ben Clayton & Doguhan Uluca in the comments for leading me to a solution.

    Some Google keywords:

    Ailment or solution for Nexus S Android debugging with the error message: Can't bind to local 8600 for debugger.

    jQuery click function doesn't work after ajax call?

    Here's the FIDDLE

    Same code as yours but it will work on dynamically created elements.

    $(document).on('click', '.deletelanguage', function () {
        alert("success");
        $('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
    });
    

    No newline at end of file

    This actually does cause a problem because line endings are automatically modified dirtying files without making any changes to them. See this post for resolution.

    git replacing LF with CRLF

    htaccess <Directory> deny from all

    You can also use RedirectMatch directive to deny access to a folder.

    To deny access to a folder, you can use the following RedirectMatch in htaccess :

     RedirectMatch 403 ^/folder/?$
    

    This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.

    To deny access to everything inside the folder, You can use this :

    RedirectMatch 403 ^/folder/.*$
    

    This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.

    How can I add a Google search box to my website?

    Sorry for replying on an older question, but I would like to clarify the last question.

    You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:

    https://www.google.com/search?g=[value from input-field]
    

    But when you search with google, you notice the following URL:

    https://www.google.nl/search?q=google+search+bar
    

    Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.

    Multiple inputs on one line

    Yes, you can.

    From cplusplus.com:

    Because these functions are operator overloading functions, the usual way in which they are called is:

       strm >> variable;
    

    Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

       strm >> variable1 >> variable2 >> variable3; //...
    

    which is the same as performing successive extractions from the same object strm.

    Just replace strm with cin.

    iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

    I was struggling with this issue for several hours, i have read every relevant topic and found out that the error was caused because under the privacy settings of my device, the camera access to my app was blocked!!! I have never denied access to camera and i don't know how it was blocked but that was the problem!

    How to test if JSON object is empty in Java

    Try:

    if (record.has("problemkey") && !record.isNull("problemkey")) {
        // Do something with object.
    }
    

    How does Zalgo text work?

    Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

    enter image description here

    OR

    y + ̆ = y̆ which actually is

    y + &#x0306; = y&#x0306;
    

    Since you can stack them one atop the other you can produce the following:


    y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

    which actually is:

    y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;
    

    The same goes for putting stuff underneath:


    y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



    that in fact is:

    y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;
    

    In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

    More about it here

    To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

    _x000D_
    _x000D_
    for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
    _x000D_
    _x000D_
    _x000D_

    Also check em out



    Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

    Why is my Button text forced to ALL CAPS on Lollipop?

    add this line in style

        <item name="android:textAllCaps">false</item>
    

    Replacing Numpy elements if condition is met

    >>> import numpy as np
    >>> a = np.random.randint(0, 5, size=(5, 4))
    >>> a
    array([[4, 2, 1, 1],
           [3, 0, 1, 2],
           [2, 0, 1, 1],
           [4, 0, 2, 3],
           [0, 0, 0, 2]])
    >>> b = a < 3
    >>> b
    array([[False,  True,  True,  True],
           [False,  True,  True,  True],
           [ True,  True,  True,  True],
           [False,  True,  True, False],
           [ True,  True,  True,  True]], dtype=bool)
    >>> 
    >>> c = b.astype(int)
    >>> c
    array([[0, 1, 1, 1],
           [0, 1, 1, 1],
           [1, 1, 1, 1],
           [0, 1, 1, 0],
           [1, 1, 1, 1]])
    

    You can shorten this with:

    >>> c = (a < 3).astype(int)
    

    C# - using List<T>.Find() with custom objects

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

            // Find a book by its ID.
            Book result = Books.Find(
            delegate(Book bk)
            {
                return bk.ID == IDtoFind;
            }
            );
            if (result != null)
            {
                DisplayResult(result, "Find by ID: " + IDtoFind);   
            }
            else
            {
                Console.WriteLine("\nNot found: {0}", IDtoFind);
            }
    

    Changing date format in R

    You could also use the parse_date_time function from the lubridate package:

    library(lubridate)
    day<-"31/08/2011"
    as.Date(parse_date_time(day,"dmy"))
    [1] "2011-08-31"
    

    parse_date_time returns a POSIXct object, so we use as.Date to get a date object. The first argument of parse_date_time specifies a date vector, the second argument specifies the order in which your format occurs. The orders argument makes parse_date_time very flexible.

    Switch case with fallthrough?

    Recent bash versions allow fall-through by using ;& in stead of ;;: they also allow resuming the case checks by using ;;& there.

    for n in 4 14 24 34
    do
      echo -n "$n = "
      case "$n" in
       3? )
         echo -n thirty-
         ;;&   #resume (to find ?4 later )
       "24" )
         echo -n twenty-
         ;&   #fallthru
       "4" | [13]4)
         echo -n four 
         ;;&  # resume ( to find teen where needed )
       "14" )
         echo -n teen
      esac
      echo 
    done
    

    sample output

    4 = four
    14 = fourteen
    24 = twenty-four
    34 = thirty-four
    

    Best Python IDE on Linux

    Probably the new PyCharm from the makers of IntelliJ and ReSharper.

    Component is not part of any NgModule or the module has not been imported into your module

    In my case, i imported wrong, In module place instead of importing module(DemoModule) imported routing module(DemoRoutingModule)

    Wrong Import:

    const routes: Routes = [
      {
      path: '', component: ContentComponent,
      children: [
      { path: '', redirectTo: 'demo' },
      { path: 'demo', loadChildren : () => import('../content/demo/demo-routing.module').then(m => m.DemoRoutingModule)}]
      }
    ];
    
    

    Right Code

    const routes: Routes = [
      {
      path: '', component: ContentComponent,
      children: [
      { path: '', redirectTo: 'demo' },
      { path: 'demo', loadChildren : () => import('../content/demo/demo.module').then(m => m.DemoModule)}]
      }
    ];
    

    Using textures in THREE.js

    By the time the image is loaded, the renderer has already drawn the scene, hence it is too late. The solution is to change

    texture = THREE.ImageUtils.loadTexture('crate.gif'),
    

    into

    texture = THREE.ImageUtils.loadTexture('crate.gif', {}, function() {
        renderer.render(scene);
    }),
    

    for-in statement

    edit 2018: This is outdated, js and typescript now have for..of loops.
    http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


    The book "TypeScript Revealed" says

    "You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

    // standard for loop
    for (var i = 0; i < actors.length; i++)
    {
      console.log(actors[i]);
    }
    
    // for..in loop
    for (var actor in actors)
    {
      console.log(actor);
    }
    

    "

    Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

    map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

    this.notes = arr.map(state => new Note(state));
    

    My wish list to TypeScript;

    1. Generic collections
    2. Iterators (IEnumerable, IEnumerator interfaces would be best)

    How to get a path to a resource in a Java JAR file

    When in a jar file, the resource is located absolutely in the package hierarchy (not file system hierarchy). So if you have class com.example.Sweet loading a resource named "./default.conf" then the resource's name is specified as "/com/example/default.conf".

    But if it's in a jar then it's not a File ...

    Compiler error: memset was not declared in this scope

    You should include <string.h> (or its C++ equivalent, <cstring>).

    ADB No Devices Found

    1. Go to device manager and check hardware id's.
    2. Check if the usb.inf file has the device listed in it
    3. If not, add the device hardware id and install it from the device manager.

    Switch statement fall-through...should it be allowed?

    It may depend on what you consider fallthrough. I'm ok with this sort of thing:

    switch (value)
    {
      case 0:
        result = ZERO_DIGIT;
        break;
    
      case 1:
      case 3:
      case 5:
      case 7:
      case 9:
         result = ODD_DIGIT;
         break;
    
      case 2:
      case 4:
      case 6:
      case 8:
         result = EVEN_DIGIT;
         break;
    }
    

    But if you have a case label followed by code that falls through to another case label, I'd pretty much always consider that evil. Perhaps moving the common code to a function and calling from both places would be a better idea.

    And please note that I use the C++ FAQ definition of "evil"

    How to handle ETIMEDOUT error?

    In case if you are using node js, then this could be the possible solution

    const express = require("express");
    const app = express();
    const server = app.listen(8080);
    server.keepAliveTimeout = 61 * 1000;
    

    https://medium.com/hk01-tech/running-eks-in-production-for-2-years-the-kubernetes-journey-at-hk01-68130e603d76

    How to prevent a click on a '#' link from jumping to top of page?

    you can even write it just like this:

    <a href="javascript:void(0);"></a>
    

    im not sure its a better way but it is a way :)

    Can't connect to local MySQL server through socket '/tmp/mysql.sock

    Looked around online too long not to contribute. After trying to type in the mysql prompt from the command line, I was continuing to receive this message:

    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

    This was due to the fact that my local mysql server was no longer running. In order to restart the server, I navigated to

    shell> cd /user/local/bin
    

    where my mysql.server was located. From here, simply type:

    shell> mysql.server start
    

    This will relaunch the local mysql server.

    From there you can reset the root password if need be..

    mysql> UPDATE mysql.user SET Password=PASSWORD('MyNewPass')
    ->                   WHERE User='root';
    mysql> FLUSH PRIVILEGES;
    

    DATEDIFF function in Oracle

    We can directly subtract dates to get difference in Days.

        SET SERVEROUTPUT ON ;
        DECLARE
            V_VAR NUMBER;
        BEGIN
             V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
             DBMS_OUTPUT.PUT_LINE(V_VAR);
        END;
    

    How to lazy load images in ListView in Android

    Update: Note that this answer is pretty ineffective now. The Garbage Collector acts aggressively on SoftReference and WeakReference, so this code is NOT suitable for new apps. (Instead, try libraries like Universal Image Loader suggested in other answers.)

    Thanks to James for the code, and Bao-Long for the suggestion of using SoftReference. I implemented the SoftReference changes on James' code. Unfortunately SoftReferences caused my images to be garbage collected too quickly. In my case it was fine without the SoftReference stuff, because my list size is limited and my images are small.

    There's a discussion from a year ago regarding the SoftReferences on google groups: link to thread. As a solution to the too-early garbage collection, they suggest the possibility of manually setting the VM heap size using dalvik.system.VMRuntime.setMinimumHeapSize(), which is not very attractive to me.

    public DrawableManager() {
        drawableMap = new HashMap<String, SoftReference<Drawable>>();
    }
    
    public Drawable fetchDrawable(String urlString) {
        SoftReference<Drawable> drawableRef = drawableMap.get(urlString);
        if (drawableRef != null) {
            Drawable drawable = drawableRef.get();
            if (drawable != null)
                return drawable;
            // Reference has expired so remove the key from drawableMap
            drawableMap.remove(urlString);
        }
    
        if (Constants.LOGGING) Log.d(this.getClass().getSimpleName(), "image url:" + urlString);
        try {
            InputStream is = fetch(urlString);
            Drawable drawable = Drawable.createFromStream(is, "src");
            drawableRef = new SoftReference<Drawable>(drawable);
            drawableMap.put(urlString, drawableRef);
            if (Constants.LOGGING) Log.d(this.getClass().getSimpleName(), "got a thumbnail drawable: " + drawable.getBounds() + ", "
                    + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
                    + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
            return drawableRef.get();
        } catch (MalformedURLException e) {
            if (Constants.LOGGING) Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
            return null;
        } catch (IOException e) {
            if (Constants.LOGGING) Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
            return null;
        }
    }
    
    public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
        SoftReference<Drawable> drawableRef = drawableMap.get(urlString);
        if (drawableRef != null) {
            Drawable drawable = drawableRef.get();
            if (drawable != null) {
                imageView.setImageDrawable(drawableRef.get());
                return;
            }
            // Reference has expired so remove the key from drawableMap
            drawableMap.remove(urlString);
        }
    
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                imageView.setImageDrawable((Drawable) message.obj);
            }
        };
    
        Thread thread = new Thread() {
            @Override
            public void run() {
                //TODO : set imageView to a "pending" image
                Drawable drawable = fetchDrawable(urlString);
                Message message = handler.obtainMessage(1, drawable);
                handler.sendMessage(message);
            }
        };
        thread.start();
    }
    

    How to get list of all installed packages along with version in composer?

    You can run composer show -i (short for --installed).

    In the latest version just use composer show.

    The -i options has been deprecated.

    You can also use the global instalation of composer: composer global show

    Correct way to find max in an Array in Swift

    Update: This should probably be the accepted answer since maxElement appeared in Swift.


    Use the almighty reduce:

    let nums = [1, 6, 3, 9, 4, 6];
    let numMax = nums.reduce(Int.min, { max($0, $1) })
    

    Similarly:

    let numMin = nums.reduce(Int.max, { min($0, $1) })
    

    reduce takes a first value that is the initial value for an internal accumulator variable, then applies the passed function (here, it's anonymous) to the accumulator and each element of the array successively, and stores the new value in the accumulator. The last accumulator value is then returned.

    Comparing Class Types in Java

    Try this:

    MyObject obj = new MyObject();
    if(obj instanceof MyObject){System.out.println("true");} //true
    

    Because of inheritance this is valid for interfaces, too:

    class Animal {}
    class Dog extends Animal {}    
    
    Dog obj = new Dog();
    Animal animal = new Dog();
    if(obj instanceof Animal){System.out.println("true");} //true
    if(animal instanceof Animal){System.out.println("true");} //true
    if(animal instanceof Dog){System.out.println("true");} //true
    

    For further reading on instanceof: http://mindprod.com/jgloss/instanceof.html

    What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

    To find them, you can use this

    ;WITH cte AS
    (
       SELECT 0 AS CharCode
       UNION ALL
       SELECT CharCode + 1 FROM cte WHERE CharCode <31
    )
    SELECT
       *
    FROM
       mytable T
         cross join cte
    WHERE
       EXISTS (SELECT *
            FROM mytable Tx
            WHERE Tx.PKCol = T.PKCol
                 AND
                  Tx.MyField LIKE '%' + CHAR(cte.CharCode) + '%'
             )
    

    Replacing the EXISTS with a JOIN will allow you to REPLACE them, but you'll get multiple rows... I can't think of a way around that...

    DateDiff to output hours and minutes

    I would make your final select as:

    SELECT    EmplID
            , EmplName
            , InTime
            , [TimeOut]
            , [DateVisited]
            , CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60) + ':' +
              RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
              as TotalHours
    from times
    Order By EmplID, DateVisited 
    

    Any solution trying to use DATEDIFF(hour,... is bound to be complicated (if it's correct) because DATEDIFF counts transitions - DATEDIFF(hour,...09:59',...10:01') will return 1 because of the transition of the hour from 9 to 10. So I'm just using DATEDIFF on minutes.

    The above can still be subtly wrong if seconds are involved (it can slightly overcount because its counting minute transitions) so if you need second or millisecond accuracy you need to adjust the DATEDIFF to use those units and then apply suitable division constants (as per the hours one above) to just return hours and minutes.

    Does bootstrap have builtin padding and margin classes?

    These spacing notations are quite effective in custom changes. You can also use negative values there too. Official

    Though we can use them whenever we want. Bootstrap Spacing

    Transition color fade on hover?

    For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:

    _x000D_
    _x000D_
    .field-error {_x000D_
        color: #f44336;_x000D_
        padding: 2px 5px;_x000D_
        position: absolute;_x000D_
        font-size: small;_x000D_
        background-color: white;_x000D_
    }_x000D_
    _x000D_
    .highlighter {_x000D_
        animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
        -moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
        -webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
        -o-animation: fadeoutBg 3s; /* Opera */_x000D_
    }_x000D_
    _x000D_
    @keyframes fadeoutBg {_x000D_
        from { background-color: lightgreen; } /** from color **/_x000D_
        to { background-color: white; } /** to color **/_x000D_
    }_x000D_
    _x000D_
    @-moz-keyframes fadeoutBg { /* Firefox */_x000D_
        from { background-color: lightgreen; }_x000D_
        to { background-color: white; }_x000D_
    }_x000D_
    _x000D_
    @-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
        from { background-color: lightgreen; }_x000D_
        to { background-color: white; }_x000D_
    }_x000D_
    _x000D_
    @-o-keyframes fadeoutBg { /* Opera */_x000D_
        from { background-color: lightgreen; }_x000D_
        to { background-color: white; }_x000D_
    }
    _x000D_
    <div class="field-error highlighter">File name already exists.</div>
    _x000D_
    _x000D_
    _x000D_

    Calculate relative time in C#

    I think there is already a number of answers related to this post, but one can use this which is easy to use just like plugin and also easily readable for programmers. Send your specific date, and get its value in string form:

    public string RelativeDateTimeCount(DateTime inputDateTime)
    {
        string outputDateTime = string.Empty;
        TimeSpan ts = DateTime.Now - inputDateTime;
    
        if (ts.Days > 7)
        { outputDateTime = inputDateTime.ToString("MMMM d, yyyy"); }
    
        else if (ts.Days > 0)
        {
            outputDateTime = ts.Days == 1 ? ("about 1 Day ago") : ("about " + ts.Days.ToString() + " Days ago");
        }
        else if (ts.Hours > 0)
        {
            outputDateTime = ts.Hours == 1 ? ("an hour ago") : (ts.Hours.ToString() + " hours ago");
        }
        else if (ts.Minutes > 0)
        {
            outputDateTime = ts.Minutes == 1 ? ("1 minute ago") : (ts.Minutes.ToString() + " minutes ago");
        }
        else outputDateTime = "few seconds ago";
    
        return outputDateTime;
    }