Programs & Examples On #Error console

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Height of status bar in Android

the height of the status bar is 24dp in android 6.0

 <!-- Height of the status bar -->
 <dimen name="status_bar_height">24dp</dimen>
 <!-- Height of the bottom navigation / system bar. -->
 <dimen name="navigation_bar_height">48dp</dimen>

you can find the answer in the source code: frameworks\base\core\res\res\values\dimens.xml

Comparing two strings in C?

You try and compare pointers here, not the contents of what is pointed to (ie, your characters).

You must use either memcmp or str{,n}cmp to compare the contents.

How to read a CSV file from a URL with Python?

This question is tagged python-2.x so it didn't seem right to tamper with the original question, or the accepted answer. However, Python 2 is now unsupported, and this question still has good google juice for "python csv urllib", so here's an updated Python 3 solution.

It's now necessary to decode urlopen's response (in bytes) into a valid local encoding, so the accepted answer has to be modified slightly:

import csv, urllib.request

url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib.request.urlopen(url)
lines = [l.decode('utf-8') for l in response.readlines()]
cr = csv.reader(lines)

for row in cr:
    print(row)

Note the extra line beginning with lines =, the fact that urlopen is now in the urllib.request module, and print of course requires parentheses.

It's hardly advertised, but yes, csv.reader can read from a list of strings.

And since someone else mentioned pandas, here's a one-liner to display the CSV in a console-friendly output:

python3 -c 'import pandas
df = pandas.read_csv("http://winterolympicsmedals.com/medals.csv")
print(df.to_string())'

(Yes, it's three lines, but you can copy-paste it as one command. ;)

How to check if ZooKeeper is running or up from command prompt?

To check if Zookeeper is accessible. One method is to simply telnet to the proper port and execute the stats command.

root@host:~# telnet localhost 2181
Trying 127.0.0.1...
Connected to myhost.
Escape character is '^]'.
stats
Zookeeper version: 3.4.3-cdh4.0.1--1, built on 06/28/2012 23:59 GMT
Clients:

Latency min/avg/max: 0/0/677
Received: 4684478
Sent: 4687034
Outstanding: 0
Zxid: 0xb00187dd0
Mode: leader
Node count: 127182
Connection closed by foreign host.

Programmatically set image to UIImageView with Xcode 6.1/Swift

In Swift 4, if the image is returned as nil.

Click on image, on the right hand side (Utilities) -> Check Target Membership

Why an interface can not implement another interface?

Hope this will help you a little what I have learned in oops (core java) during my college.

Implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible. An interface can however extend another interface, which means it can add more methods and inherit its type.

Here is an example below, this is my understanding and what I have learnt in oops.

interface ParentInterface{  
        void myMethod();  
}  

interface SubInterface extends ParentInterface{  
        void anotherMethod();  
}  

and keep one thing in a mind one interface can only extend another interface and if you want to define it's function on some class then only a interface in implemented eg below

public interface Dog
{
    public boolean Barks();

    public boolean isGoldenRetriever();
}

Now, if a class were to implement this interface, this is what it would look like:

public class SomeClass implements Dog
{
    public boolean Barks{
    // method definition here

    }

    public boolean isGoldenRetriever{
    // method definition here
    }
}

and if a abstract class has some abstract function define and declare and you want to define those function or you can say implement those function then you suppose to extends that class because abstract class can only be extended. here is example below.

public abstract class MyAbstractClass {

    public abstract void abstractMethod();
}

Here is an example subclass of MyAbstractClass:

public class MySubClass extends MyAbstractClass {

    public void abstractMethod() {
        System.out.println("My method implementation");
    }
}

Check table exist or not before create it in Oracle

Well there are lot of answeres already provided and lot are making sense too.

Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.

I came across similar situation today and here is very simple query I came up with...

declare
begin
  execute immediate '
    create table "TBL" ("ID" number not null)';
  exception when others then
    if SQLCODE = -955 then null; else raise; end if;
end;
/

955 is failure code.

This is simple, if exception come while running query it will be suppressed. and you can use same for SQL or Oracle.

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

You should in fact do both, so that all browsers will find the icon.

Naming the file "favicon.ico" and putting it in the root of your website is the method "discouraged" by W3C:

Method 2 (Discouraged): Putting the favicon at a predefined URI
A second method for specifying a favicon relies on using a predefined URI to identify the image: "/favicon", which is relative to the server root. This method works because some browsers have been programmed to look for favicons using that URI.
W3C - How to add a favicon to your site

So, to cover all situations, I always do that in addition to the recommended method of adding a "rel" attribute and pointing it to the same .ico file.

Solving a "communications link failure" with JDBC and MySQL

Had the same. Removing port helped in my case, so I left it as jdbc:mysql://localhost/

Create an empty data.frame

I keep this function handy for whenever I need it, and change the column names and classes to suit the use case:

make_df <- function() { data.frame(name=character(),
                     profile=character(),
                     sector=character(),
                     type=character(),
                     year_range=character(),
                     link=character(),
                     stringsAsFactors = F)
}

make_df()
[1] name       profile    sector     type       year_range link      
<0 rows> (or 0-length row.names)

Set database from SINGLE USER mode to MULTI USER

You can add the option to rollback your change immediately.

ALTER DATABASE BARDABARD
SET MULTI_USER
WITH ROLLBACK IMMEDIATE
GO

How to include jQuery in ASP.Net project?

You can include the script file directly in your page/master page, etc using:

 <script type="text/javascript" src="/scripts/jquery.min.js"></script> 

Us use a Content Delivery network like Google or Microsoft:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 

or:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>     

How to replace master branch in Git, entirely, from another branch?

What about using git branch -m to rename the master branch to another one, then rename seotweaks branch to master? Something like this:

git branch -m master old-master
git branch -m seotweaks master
git push -f origin master

This might remove commits in origin master, please check your origin master before running git push -f origin master.

Hot deploy on JBoss - how do I make JBoss "see" the change?

Hot deployment is stable only for changes on static parts of the application (jsf, xhtml, etc.).

Here is a working solution, according to JBoss AS 7.1.1.Final:

  • Build your project.
  • Navigate to [JBOSS_HOME]/standalone/tmp/vfs.
  • Open the most recently modified folder named "deployment[some_alphanumeric_values]", i.e. "deployment344b1c870c8edbd".
  • Navigate to the specific view that you want to edit (usually, this is included into the packaged .war folder) and open it with a text editor (i.e. Notepad++).
  • Make the changes you want and save the file.
  • Refresh the respective page on your browser. The changes should be visible now.
  • When finished, don't forget to copy these changes to your actual development environment, rebuild and redeploy.

    How do I connect to mongodb with node.js (and authenticate)?

    With the link provided by @mattdlockyer as reference, this worked for me:

    var mongo = require('mongodb');
    var server = new mongo.Server(host, port, options);
    db = new mongo.Db(mydb, server, {fsync:true});
    db.open(function(err, db) {
        if(!err) {
            console.log("Connected to database");
            db.authenticate(user, password, function(err, res) {
                if(!err) {
                    console.log("Authenticated");
                } else {
                    console.log("Error in authentication.");
                    console.log(err);
                }
            });
        } else {
            console.log("Error in open().");
            console.log(err);
        };
    });
    
    exports.testMongo = function(req, res){
        db.collection( mycollection, function(err, collection) {
            collection.find().toArray(function(err, items) {
                res.send(items);
            });
        });
    };
    

    How to remove all MySQL tables from the command-line without DROP database permissions?

    The @Devart's version is correct, but here are some improvements to avoid having error. I've edited the @Devart's answer, but it was not accepted.

    SET FOREIGN_KEY_CHECKS = 0;
    SET GROUP_CONCAT_MAX_LEN=32768;
    SET @tables = NULL;
    SELECT GROUP_CONCAT('`', table_name, '`') INTO @tables
      FROM information_schema.tables
      WHERE table_schema = (SELECT DATABASE());
    SELECT IFNULL(@tables,'dummy') INTO @tables;
    
    SET @tables = CONCAT('DROP TABLE IF EXISTS ', @tables);
    PREPARE stmt FROM @tables;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    SET FOREIGN_KEY_CHECKS = 1;
    

    This script will not raise error with NULL result in case when you already deleted all tables in the database by adding at least one nonexistent - "dummy" table.

    And it fixed in case when you have many tables.

    And This small change to drop all view exist in the Database

    SET FOREIGN_KEY_CHECKS = 0;
    SET GROUP_CONCAT_MAX_LEN=32768;
    SET @views = NULL;
    SELECT GROUP_CONCAT('`', TABLE_NAME, '`') INTO @views
      FROM information_schema.views
      WHERE table_schema = (SELECT DATABASE());
    SELECT IFNULL(@views,'dummy') INTO @views;
    
    SET @views = CONCAT('DROP VIEW IF EXISTS ', @views);
    PREPARE stmt FROM @views;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    SET FOREIGN_KEY_CHECKS = 1;
    

    It assumes that you run the script from Database you want to delete. Or run this before:

    USE REPLACE_WITH_DATABASE_NAME_YOU_WANT_TO_DELETE;
    

    Thank you to Steve Horvath to discover the issue with backticks.

    What are the use cases for selecting CHAR over VARCHAR in SQL?

    Many people have pointed out that if you know the exact length of the value using CHAR has some benefits. But while storing US states as CHAR(2) is great today, when you get the message from sales that 'We have just made our first sale to Australia', you are in a world of pain. I always send to overestimate how long I think fields will need to be rather than making an 'exact' guess to cover for future events. VARCHAR will give me more flexibility in this area.

    Why are exclamation marks used in Ruby methods?

    This naming convention is lifted from Scheme.

    1.3.5 Naming conventions

    By convention, the names of procedures that always return a boolean value usually end in ``?''. Such procedures are called predicates.

    By convention, the names of procedures that store values into previously allocated locations (see section 3.4) usually end in ``!''. Such procedures are called mutation procedures. By convention, the value returned by a mutation procedure is unspecified.

    Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

    That's the distinction between declaration and definition. Header files typically include just the declaration, and the source file contains the definition.

    In order to use something you only need to know it's declaration not it's definition. Only the linker needs to know the definition.

    So this is why you will include a header file inside one or more source files but you won't include a source file inside another.

    Also you mean #include and not import.

    Store select query's output in one array in postgres

    I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):

    SELECT ARRAY(
    SELECT column_name::text
    FROM information_schema.columns
    WHERE table_name='aean'
    )
    

    How to get the clicked link's href with jquery?

    You're looking for $(this).attr("href");

    How to check if an integer is within a range?

    Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
    But I needed a function to test if $n was between $a and $b, as described here:

    Check if $n is between $a and $b even if:
        $a < $b  
        $a > $b
        $a = $b
    
    All numbers can be real, not only integer.
    

    There is an easy way to test.
    I base the test it in the fact that ($n-$a) and ($n-$b) have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
    This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.

    function between($n, $a, $b)
    {
        return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
    }
    

    How to use Python to login to a webpage and retrieve cookies for later usage?

    Here's a version using the excellent requests library:

    from requests import session
    
    payload = {
        'action': 'login',
        'username': USERNAME,
        'password': PASSWORD
    }
    
    with session() as c:
        c.post('http://example.com/login.php', data=payload)
        response = c.get('http://example.com/protected_page.php')
        print(response.headers)
        print(response.text)
    

    Generating sql insert into for Oracle

    You might execute something like this in the database:

    select "insert into targettable(field1, field2, ...) values(" || field1 || ", " || field2 || ... || ");"
    from targettable;
    

    Something more sophisticated is here.

    Create a shortcut on Desktop

    private void CreateShortcut(string executablePath, string name)
        {
            CMDexec("echo Set oWS = WScript.CreateObject('WScript.Shell') > CreateShortcut.vbs");
            CMDexec("echo sLinkFile = '" + Environment.GetEnvironmentVariable("homedrive") + "\\users\\" + Environment.GetEnvironmentVariable("username") + "\\desktop\\" + name + ".ink' >> CreateShortcut.vbs");
            CMDexec("echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs");
            CMDexec("echo oLink.TargetPath = '" + executablePath + "' >> CreateShortcut.vbs");
            CMDexec("echo oLink.Save >> CreateShortcut.vbs");
            CMDexec("cscript CreateShortcut.vbs");
            CMDexec("del CreateShortcut.vbs");
        }
    

    How to modify WooCommerce cart, checkout pages (main theme portion)

    You can use function: wc_get_page_id( 'cart' ) to get the ID of the page. This function will use the page setup as 'cart' page and not the slug. Meaning it will keep working also when you setup a different url for your 'cart' on the settings page. This works for all kind of Woocommerce special page, like 'checkout', 'shop' etc.

    example:

    if (wc_get_page_id( 'cart' ) == get_the_ID()) {
      // Do something.
    }
    

    What are examples of TCP and UDP in real life?

    TCP guarantees (in-order) packet delivery. UDP doesn't.

    TCP - used for traffic that you need all the data for. i.e HTML, pictures, etc. UDP - used for traffic that doesn't suffer much if a packet is dropped, i.e. video & voice streaming, some data channels of online games, etc.

    Align text to the bottom of a div

    Flex Solution

    It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

    _x000D_
    _x000D_
    .wrap {_x000D_
      height: 200px;_x000D_
      width: 200px;_x000D_
      border: 1px solid #aaa;_x000D_
      margin: 10px;_x000D_
      display: flex;_x000D_
    }_x000D_
    _x000D_
    .wrap span {_x000D_
      align-self: flex-end;_x000D_
    }
    _x000D_
    <div class="wrap">_x000D_
      <span>Align me to the bottom</span>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


    Old Solution (Valid if you are not willing to use flex)

    If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

    _x000D_
    _x000D_
    div {_x000D_
      display: table-cell;_x000D_
      vertical-align: bottom;_x000D_
      border: 1px solid #f00;_x000D_
      height: 100px;_x000D_
      width: 100px;_x000D_
    }
    _x000D_
    <div>Hello</div>
    _x000D_
    _x000D_
    _x000D_

    (Or JSFiddle)

    Detect element content changes with jQuery

    We can achieve this by using Mutation Events. According to www.w3.org, The mutation event module is designed to allow notification of any changes to the structure of a document, including attr and text modifications. For more detail MUTATION EVENTS

    For Example :

    $("body").on('DOMSubtreeModified', "#content", function() {
        alert('Content Modified'); // do something
    });
    

    How to get data from database in javascript based on the value passed to the function

    Try the following:

    <script> 
     //Functions to open database and to create, insert data into tables
    
     getSelectedRow = function(val)
        {
            db.transaction(function(transaction) {
                  transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);
    
            });
        };
        selectedRowValues = function(transaction,results)
        {
             for(var i = 0; i < results.rows.length; i++)
             {
                 var row = results.rows.item(i);
                 alert(row['number']);
                 alert(row['name']);                 
             }
        };
    </script>
    

    You don't have access to javascript variable names in SQL, you must pass the values to the Database.

    How to deal with SettingWithCopyWarning in Pandas

    The SettingWithCopyWarning was created to flag potentially confusing "chained" assignments, such as the following, which does not always work as expected, particularly when the first selection returns a copy. [see GH5390 and GH5597 for background discussion.]

    df[df['A'] > 2]['B'] = new_val  # new_val not set in df
    

    The warning offers a suggestion to rewrite as follows:

    df.loc[df['A'] > 2, 'B'] = new_val
    

    However, this doesn't fit your usage, which is equivalent to:

    df = df[df['A'] > 2]
    df['B'] = new_val
    

    While it's clear that you don't care about writes making it back to the original frame (since you are overwriting the reference to it), unfortunately this pattern cannot be differentiated from the first chained assignment example. Hence the (false positive) warning. The potential for false positives is addressed in the docs on indexing, if you'd like to read further. You can safely disable this new warning with the following assignment.

    import pandas as pd
    pd.options.mode.chained_assignment = None  # default='warn'
    

    Other Resources

    Just get column names from hive table

    use desc tablename from Hive CLI or beeline to get all the column names. If you want the column names in a file then run the below command from the shell.

    $ hive -e 'desc dbname.tablename;' > ~/columnnames.txt
    

    where dbname is the name of the Hive database where your table is residing You can find the file columnnames.txt in your root directory.

    $cd ~
    $ls
    

    .m2 , settings.xml in Ubuntu

    You can find your maven files here:

    cd ~/.m2
    

    Probably you need to copy settings.xml in your .m2 folder:

    cp /usr/local/bin/apache-maven-2.2.1/conf/settings.xml .m2/
    

    If no .m2 folder exists:

    mkdir -p ~/.m2
    

    Append an int to a std::string

    The std::string::append() method expects its argument to be a NULL terminated string (char*).

    There are several approaches for producing a string containg an int:

    • std::ostringstream

      #include <sstream>
      
      std::ostringstream s;
      s << "select logged from login where id = " << ClientID;
      std::string query(s.str());
      
    • std::to_string (C++11)

      std::string query("select logged from login where id = " +
                        std::to_string(ClientID));
      
    • boost::lexical_cast

      #include <boost/lexical_cast.hpp>
      
      std::string query("select logged from login where id = " +
                        boost::lexical_cast<std::string>(ClientID));
      

    MySQL Incorrect datetime value: '0000-00-00 00:00:00'

    This is what I did to solve my problem. I tested in local MySQL 5.7 ubuntu 18.04.

    set global sql_mode="NO_ENGINE_SUBSTITUTION";
    

    Before running this query globally I added a cnf file in /etc/mysql/conf.d directory. The cnf file name is mysql.cnf and codes

    [mysqld]
    sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ALLOW_INVALID_DATES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
    

    Then I restart mysql

    sudo service mysql restart
    

    Hope this can help someone.

    Bootstrap 3.0 Popovers and tooltips

    I had to do it on DOM ready

    $( document ).ready(function () { // this has to be done after the document has been rendered
        $("[data-toggle='tooltip']").tooltip({html: true}); // enable bootstrap 3 tooltips
        $('[data-toggle="popover"]').popover({
            trigger: 'hover',
            'placement': 'top',
            'show': true
        });
    });
    

    And change my load orders to be:

    • jQuery
    • jQuery UI
    • Bootstrap

    Efficient way to add spaces between characters in a string

    The most efficient way is to take input make the logic and run

    so the code is like this to make your own space maker

    need = input("Write a string:- ")
    result = ''
    for character in need:
       result = result + character + ' '
    print(result)    # to rid of space after O
    

    but if you want to use what python give then use this code

    need2 = input("Write a string:- ")
    
    print(" ".join(need2))
    

    Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

    In addition to your CORS issue, the server you are trying to access has HTTP basic authentication enabled. You can include credentials in your cross-domain request by specifying the credentials in the URL you pass to the XHR:

    url = 'http://username:[email protected]/testpage'
    

    brew install mysql on macOS

    Try solution I provided for MariaDB, high change that it works with MySQL also:

    MacOSX homebrew mysql root password

    In short, try to login with your username! not root.

    Try same name as your MacOS account username, e.g. johnsmit.

    To login as root, issue:

    mysql -u johnsmit
    

    A CORS POST request works from plain JavaScript, but why not with jQuery?

    Modify your Jquery in following way:

    $.ajax({
                url: someurl,
                contentType: 'application/json',
                data: JSONObject,
                headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
                dataType: 'json',
                type: 'POST',                
                success: function (Data) {....}
    });
    

    How can a file be copied?

    You can use one of the copy functions from the shutil package:

    ??????????????????????????????????????????????????????????????????????????????
    Function              preserves     supports          accepts     copies other
                          permissions   directory dest.   file obj    metadata  
    ------------------------------------------------------------------------------
    shutil.copy              ?             ?                 ?           ?
    shutil.copy2             ?             ?                 ?           ?
    shutil.copyfile          ?             ?                 ?           ?
    shutil.copyfileobj       ?             ?                 ?           ?
    ??????????????????????????????????????????????????????????????????????????????
    

    Example:

    import shutil
    shutil.copy('/etc/hostname', '/var/tmp/testhostname')
    

    How can I control Chromedriver open window size?

    If you are using Clojure and https://github.com/semperos/clj-webdriver you can use this snippet to resize the browser.

    (require '[clj-webdriver.taxi :as taxi])
    
    ; Open browser
    (taxi/set-driver! {:browser :chrome} "about:blank")
    
    ; Resize browser
    (-> taxi/*driver* (.webdriver) (.manage) (.window) 
      (.setSize (org.openqa.selenium.Dimension. 0 0)))
    

    What's the difference between process.cwd() vs __dirname?

    process.cwd() returns the current working directory,

    i.e. the directory from which you invoked the node command.

    __dirname returns the directory name of the directory containing the JavaScript source code file

    Where to place JavaScript in an HTML file?

    With 100k of Javascript, you should never put it inside the file. Use an external script Javascript file. There's no chance in hell you'll only ever use this amount of code in only one HTML page. Likely you're asking where you should load the Javascript file, for this you've received satisfactory answers already.

    But I'd like to point out that commonly, modern browsers accept gzipped Javascript files! Just gzip the x.js file to x.js.gz, and point to that in the src attribute. It doesn't work on the local filesystem, you need a webserver for it to work. But the savings in transferred bytes can be enormous.

    I've successfully tested it in Firefox 3, MSIE 7, Opera 9, and Google Chrome. It apparently doesn't work this way in Safari 3.

    For more info, see this blog post, and another very ancient page that nevertheless is useful because it points out that the webserver can detect whether a browser can accept gzipped Javascript, or not. If your server side can dynamically choose to send the gzipped or the plain text, you can make the page usable in all web browsers.

    How update the _id of one MongoDB Document?

    You cannot update it. You'll have to save the document using a new _id, and then remove the old document.

    // store the document in a variable
    doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})
    
    // set a new _id on the document
    doc._id = ObjectId("4c8a331bda76c559ef000004")
    
    // insert the document, using the new _id
    db.clients.insert(doc)
    
    // remove the document with the old _id
    db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})
    

    How can I change default dialog button text color in android 5

    The simpliest solution is:

    dialog.show(); //Only after .show() was called
    dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(neededColor);
    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(neededColor);
    

    Getting the first index of an object

    Using underscore you can use _.pairs to get the first object entry as a key value pair as follows:

    _.pairs(obj)[0]
    

    Then the key would be available with a further [0] subscript, the value with [1]

    Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

    The fastest way to get a count of a table is exactly what you did. There are no tricks you can do that Oracle doesn't already know about.

    There are somethings you have not told us. Namely why do you think think this should be faster?

    For example:

    1. Have you at least done an explain plan to see what Oracle is doing?
    2. How many rows are there in this table?
    3. What version of Oracle are you using? 8,9,10,11 ... 7?
    4. Have you ever run database statistics on this table?
    5. Is this a frequently updated table or batch loaded or just static data?
    6. Is this the only slow COUNT(*) you have?
    7. How long does SELECT COUNT(*) FROM Dual take?

    I'll admit I wouldn't be happy with 41 seconds but really WHY do you think it should be faster? If you tell us the table has 18 billion rows and is running on the laptop you bought from a garage sale in 2001, 41 seconds is probably not that far outside "good as it will get" unless you get better hardware. However if you say you are on Oracle 9 and you ran statistics last summer well you'll probably get a different suggestions.

    How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

    ****You can also use conditions by using this method** **

     int _moneyCounter = 0;
      void _rainMoney(){
        setState(() {
          _moneyCounter +=  100;
        });
      }
    
    new Expanded(
              child: new Center(
                child: new Text('\$$_moneyCounter', 
    
                style:new TextStyle(
                  color: _moneyCounter > 1000 ? Colors.blue : Colors.amberAccent,
                  fontSize: 47,
                  fontWeight: FontWeight.w800
                )
    
                ),
              ) 
            ),
    

    How to send a simple email from a Windows batch file?

    If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.

    I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.

    A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.

    Putting -moz-available and -webkit-fill-available in one width (css property)

    I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:

    width: 100%
    

    I had to add the CSS class into the asp:DropDownList element

    TERM environment variable not set

    Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.

    Creating files in C++

    Do this with a file stream. When a std::ofstream is closed, the file is created. I personally like the following code, because the OP only asks to create a file, not to write in it:

    #include <fstream>
    
    int main()
    {
        std::ofstream file { "Hello.txt" };
        // Hello.txt has been created here
    }
    

    The temporary variable file is destroyed right after its creation, so the stream is closed and thus the file is created.

    Git push rejected "non-fast-forward"

    Write lock on shared local repository

    I had this problem and none of above advises helped me. I was able to fetch everything correctly. But push always failed. It was a local repository located on windows directory with several clients working with it through VMWare shared folder driver. It appeared that one of the systems locked Git repository for writing. After stopping relevant VMWare system, which caused the lock everything repaired immediately. It was almost impossible to figure out, which system causes the error, so I had to stop them one by one until succeeded.

    How do I do an insert with DATETIME now inside of SQL server mgmt studioÜ

    Just use GETDATE() or GETUTCDATE() (if you want to get the "universal" UTC time, instead of your local server's time-zone related time).

    INSERT INTO [Business]
               ([IsDeleted]
               ,[FirstName]
               ,[LastName]
               ,[LastUpdated]
               ,[LastUpdatedBy])
         VALUES
               (0, 'Joe', 'Thomas', 
               GETDATE(),  <LastUpdatedBy, nvarchar(50),>)
    

    Bootstrap 3 jquery event for active tab change

    This worked for me.

    $('.nav-pills > li > a').click( function() {
        $('.nav-pills > li.active').removeClass('active');
        $(this).parent().addClass('active');
    } );
    

    How to enable assembly bind failure logging (Fusion) in .NET

    You can run this Powershell script as administrator to enable FL:

    Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name ForceLog         -Value 1               -Type DWord
    Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogFailures      -Value 1               -Type DWord
    Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogResourceBinds -Value 1               -Type DWord
    Set-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogPath          -Value 'C:\FusionLog\' -Type String
    mkdir C:\FusionLog -Force
    

    and this one to disable:

    Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name ForceLog
    Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogFailures
    Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogResourceBinds
    Remove-ItemProperty -Path HKLM:\Software\Microsoft\Fusion -Name LogPath
    

    Convert DataFrame column type from string to datetime, dd/mm/yyyy format

    The easiest way is to use to_datetime:

    df['col'] = pd.to_datetime(df['col'])
    

    It also offers a dayfirst argument for European times (but beware this isn't strict).

    Here it is in action:

    In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
    Out[11]:
    0   2005-05-23 00:00:00
    dtype: datetime64[ns]
    

    You can pass a specific format:

    In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
    Out[12]:
    0   2005-05-23
    dtype: datetime64[ns]
    

    Jquery UI tooltip does not support html content

    I solved it with a custom data tag, because a title attribute is required anyway.

    $("[data-tooltip]").each(function(i, e) {
        var tag = $(e);
        if (tag.is("[title]") === false) {
            tag.attr("title", "");
        }
    });
    
    $(document).tooltip({
        items: "[data-tooltip]",
        content: function () {
            return $(this).attr("data-tooltip");
        }
    });
    

    Like this it is html conform and the tooltips are only shown for wanted tags.

    How to debug a Flask app

    One can also use the Flask Debug Toolbar extension to get more detailed information embedded in rendered pages.

    from flask import Flask
    from flask_debugtoolbar import DebugToolbarExtension
    import logging
    
    app = Flask(__name__)
    app.debug = True
    app.secret_key = 'development key'
    
    toolbar = DebugToolbarExtension(app)
    
    @app.route('/')
    def index():
        logging.warning("See this message in Flask Debug Toolbar!")
        return "<html><body></body></html>"
    

    Start the application as follows:

    FLASK_APP=main.py FLASK_DEBUG=1 flask run
    

    How do you modify a CSS style in the code behind file for divs in ASP.NET?

    Another way to do it:

    testSpace.Style.Add("display", "none");
    

    or

    testSpace.Style["background-image"] = "url(images/foo.png)";
    

    in vb.net you can do it this way:

    testSpace.Style.Item("display") = "none"
    

    angularjs: ng-src equivalent for background-image:url(...)

    This one works for me

    <li ng-style="{'background-image':'url(/static/'+imgURL+')'}">...</li>
    

    how do you insert null values into sql server

    If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

    Oracle Insert via Select from multiple tables where one table may not have a row

    A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:

    INSERT INTO account_type_standard   
      (account_type_Standard_id, tax_status_id, recipient_id) 
    VALUES(   
      account_type_standard_seq.nextval,
      (SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
      (SELECT recipient_id FROM recipient WHERE recipient_code = ?)
    )
    

    Find files in a folder using Java

    For list out Json files from your given directory.

    import java.io.File;
        import java.io.FilenameFilter;
    
        public class ListOutFilesInDir {
            public static void main(String[] args) throws Exception {
    
                File[] fileList = getFileList("directory path");
    
                for(File file : fileList) {
                    System.out.println(file.getName());
                }
            }
    
            private static File[] getFileList(String dirPath) {
                File dir = new File(dirPath);   
    
                File[] fileList = dir.listFiles(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.endsWith(".json");
                    }
                });
                return fileList;
            }
        }
    

    JQuery - $ is not defined

    Something that I didn't find here, but did happen to me. Make sure you don't have the jQuery slim version included, as that version of the jQuery library doesn't include the Ajax functionality.

    The result is that "$" works, but $.get for example returns an error message stating that that function is undefined.

    Solution: include the full version of jQuery instead.

    Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

    This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states

    The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....

    application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.

    Solution

    Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.

    fork: retry: Resource temporarily unavailable

    Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

    watch -n 5 -d "ps -eL <java_pid> | wc -l"
    

    to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

    How do I break out of nested loops in Java?

    If you don't like breaks and gotos, you can use a "traditional" for loop instead the for-in, with an extra abort condition:

    int a, b;
    bool abort = false;
    for (a = 0; a < 10 && !abort; a++) {
        for (b = 0; b < 10 && !abort; b++) {
            if (condition) {
                doSomeThing();
                abort = true;
            }
        }
    }
    

    Clearing Magento Log Data

    Cleaning the Magento Logs using SSH :

    login to shell(SSH) panel and go with root/shell folder.

    execute the below command inside the shell folder

    php -f log.php clean
    

    enter this command to view the log data's size

    php -f log.php status

    This method will help you to clean the log data's very easy way.

    Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

    Another reason could be that you have changed the machine from which you're submitting the app. Or the user account on the machine. The new machine may lack the private key and/or certificate for the App Store. Although a certificate with the correct name is displayed in Xcode.

    In this case, go to https://developer.apple.com -> certificates, use the plus sign (+) to add a new certificate (distribution), and follow the steps to request a certificate for the private key on your current machine. After installing the certificate, authentication may work.

    How to declare a constant map in Golang?

    You may emulate a map with a closure:

    package main
    
    import (
        "fmt"
    )
    
    // http://stackoverflow.com/a/27457144/10278
    
    func romanNumeralDict() func(int) string {
        // innerMap is captured in the closure returned below
        innerMap := map[int]string{
            1000: "M",
            900:  "CM",
            500:  "D",
            400:  "CD",
            100:  "C",
            90:   "XC",
            50:   "L",
            40:   "XL",
            10:   "X",
            9:    "IX",
            5:    "V",
            4:    "IV",
            1:    "I",
        }
    
        return func(key int) string {
            return innerMap[key]
        }
    }
    
    func main() {
        fmt.Println(romanNumeralDict()(10))
        fmt.Println(romanNumeralDict()(100))
    
        dict := romanNumeralDict()
        fmt.Println(dict(400))
    }
    

    Try it on the Go playground

    How to change font size in Eclipse for Java text editors?

    For Eclipse Neon

    To Increase Ctrl +

    To reduce Ctrl -

    shortcut for font eclipse

    Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

    Using the stat.* bit masks does seem to me the most portable and explicit way of doing this. But on the other hand, I often forget how best to handle that. So, here's an example of masking out the 'group' and 'other' permissions and leaving 'owner' permissions untouched. Using bitmasks and subtraction is a useful pattern.

    import os
    import stat
    def chmodme(pn):
        """Removes 'group' and 'other' perms. Doesn't touch 'owner' perms."""
        mode = os.stat(pn).st_mode
        mode -= (mode & (stat.S_IRWXG | stat.S_IRWXO))
        os.chmod(pn, mode)
    

    Why doesn't Java support unsigned ints?

    I can think of one unfortunate side-effect. In java embedded databases, the number of ids you can have with a 32bit id field is 2^31, not 2^32 (~2billion, not ~4billion).

    how to make a specific text on TextView BOLD

    Here is my complete solution for dynamic String values with case check.

    /**
     * Makes a portion of String formatted in BOLD.
     *
     * @param completeString       String from which a portion needs to be extracted and formatted.<br> eg. I am BOLD.
     * @param targetStringToFormat Target String value to format. <br>eg. BOLD
     * @param matchCase Match by target character case or not. If true, BOLD != bold
     * @return A string with a portion formatted in BOLD. <br> I am <b>BOLD</b>.
     */
    public static SpannableStringBuilder formatAStringPortionInBold(String completeString, String targetStringToFormat, boolean matchCase) {
        //Null complete string return empty
        if (TextUtils.isEmpty(completeString)) {
            return new SpannableStringBuilder("");
        }
    
        SpannableStringBuilder str = new SpannableStringBuilder(completeString);
        int start_index = 0;
    
        //if matchCase is true, match exact string
        if (matchCase) {
            if (TextUtils.isEmpty(targetStringToFormat) || !completeString.contains(targetStringToFormat)) {
                return str;
            }
    
            start_index = str.toString().indexOf(targetStringToFormat);
        } else {
            //else find in lower cases
            if (TextUtils.isEmpty(targetStringToFormat) || !completeString.toLowerCase().contains(targetStringToFormat.toLowerCase())) {
                return str;
            }
    
            start_index = str.toString().toLowerCase().indexOf(targetStringToFormat.toLowerCase());
        }
    
        int end_index = start_index + targetStringToFormat.length();
        str.setSpan(new StyleSpan(BOLD), start_index, end_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return str;
    }
    

    Eg. completeString = "I am BOLD"

    CASE I if *targetStringToFormat* = "bold" and *matchCase* = true

    returns "I am BOLD" (since bold != BOLD)

    CASE II if *targetStringToFormat* = "bold" and *matchCase* = false

    returns "I am BOLD"

    To Apply:

    myTextView.setText(formatAStringPortionInBold("I am BOLD", "bold", false))
    

    Hope that helps!

    Installing Java on OS X 10.9 (Mavericks)

    If you only want to install the latest official JRE from Oracle, you can get it there, install it, and export the new JAVA_HOME in the terminal.

    That's the cleanest way I found to install the latest JRE.

    You can add the export JAVA_HOME line in your .bashrc to have java permanently in your Terminal:

    echo export JAVA_HOME=\"/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home\" >> ~/.bashrc
    

    Comparing results with today's date?

    For me the query that is working, if I want to compare with DrawDate for example is:

    CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
    

    This is comparing results with today's date.

    or the whole query:

    SELECT TOP (1000) *
    FROM test
    where DrawName != 'NULL' and CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
    order by id desc
    

    Get current URL/URI without some of $_GET variables

    For Yii2: This should be safer Yii::$app->request->absoluteUrl rather than Yii::$app->request->url

    How to get "their" changes in the middle of conflicting Git rebase?

    You want to use:

    git checkout --ours foo/bar.java
    git add foo/bar.java
    

    If you rebase a branch feature_x against main (i.e. running git rebase main while on branch feature_x), during rebasing ours refers to main and theirs to feature_x.

    As pointed out in the git-rebase docs:

    Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.

    For further details read this thread.

    Can I store images in MySQL

    You will need to store the image in the database as a BLOB.

    you will want to create a column called PHOTO in your table and set it as a mediumblob.

    Then you will want to get it from the form like so:

        $data = file_get_contents($_FILES['photo']['tmp_name']);
    

    and then set the column to the value in $data.

    Of course, this is bad practice and you would probably want to store the file on the system with a name that corresponds to the users account.

    jQuery .search() to any string

    if (str.toLowerCase().indexOf("yes") >= 0)
    

    Or,

    if (/yes/i.test(str))
    

    What does the @Valid annotation indicate in Spring?

    IIRC @Valid isn't a Spring annotation but a JSR-303 annotation (which is the Bean Validation standard). What it does is it basically checks if the data that you send to the method is valid or not (it will validate the scriptFile for you).

    LinkButton Send Value to Code Behind OnClick

    Try and retrieve the text property of the link button in the code behind:

    protected void ENameLinkBtn_Click (object sender, EventArgs e)
    {
       string val = ((LinkButton)sender).Text
    }
    

    Comma separated results in SQL

    For Sql Server 2017 and later you can use the new STRING_AGG function

    https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

    The following example replaces null values with 'N/A' and returns the names separated by commas in a single result cell.

    SELECT STRING_AGG ( ISNULL(FirstName,'N/A'), ',') AS csv 
    FROM Person.Person;
    

    Here is the result set.

    John,N/A,Mike,Peter,N/A,N/A,Alice,Bob
    

    Perhaps a more common use case is to group together and then aggregate, just like you would with SUM, COUNT or AVG.

    SELECT a.articleId, title, STRING_AGG (tag, ',') AS tags 
    FROM dbo.Article AS a       
    LEFT JOIN dbo.ArticleTag AS t 
        ON a.ArticleId = t.ArticleId 
    GROUP BY a.articleId, title;
    

    Unresolved external symbol on static class members

    In my case, I was using wrong linking.
    It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
    [Usually managed code does not use dll export and import, it uses references, but that was unique situation.]

    Using column alias in WHERE clause of MySQL query produces an error

    Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. For example, the following query is illegal:

    SELECT id, COUNT(*) AS cnt FROM tbl_name WHERE cnt > 0 GROUP BY id;

    javaw.exe cannot find path

    Make sure to download these from here:

    enter image description here

    Also create PATH enviroment variable on you computer like this (if it doesn't exist already):

    1. Right click on My Computer/Computer
    2. Properties
    3. Advanced system settings (or just Advanced)
    4. Enviroment variables
    5. If PATH variable doesn't exist among "User variables" click New (Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin; <-- please check out the right version, this may differ as Oracle keeps updating Java). ; in the end enables assignment of multiple values to PATH variable.
    6. Click OK! Done

    enter image description here

    To be sure that everything works, open CMD Prompt and type: java -version to check for Java version and javac to be sure that compiler responds.

    enter image description here

    I hope this helps. Good luck!

    Binary Search Tree - Java Implementation

    This program has a functions for

    1. Add Node
    2. Display BST(Inorder)
    3. Find Element
    4. Find Successor

      class BNode{
          int data;
          BNode left, right;
      
          public BNode(int data){
              this.data = data;
              this.left = null;
              this.right = null;
          }
      }
      
      public class BST {
          static BNode root;
      
          public int add(int value){
              BNode newNode, current;
      
              newNode = new BNode(value);
              if(root == null){
                  root = newNode;
                  current = root;
              }
              else{
                  current = root;
                  while(current.left != null || current.right != null){
                      if(newNode.data < current.data){
                          if(current.left != null)
                              current = current.left;
                          else
                              break;
                      }                   
                      else{
                          if(current.right != null)
                              current = current.right;
                          else
                              break;
                      }                                           
                  }
                  if(newNode.data < current.data)
                      current.left = newNode;
                  else
                      current.right = newNode;
              }
      
              return value;
          }
      
          public void inorder(BNode root){
              if (root != null) {
                  inorder(root.left);
                  System.out.println(root.data);
                  inorder(root.right);
              }
          }
      
          public boolean find(int value){
              boolean flag = false;
              BNode current;
              current = root;
              while(current!= null){
                  if(current.data == value){
                      flag = true;
                      break;
                  }   
                  else if(current.data > value)
                      current = current.left;
                  else
                      current = current.right;
              }
              System.out.println("Is "+value+" present in tree? : "+flag);
              return flag;
          }
      
          public void successor(int value){
              BNode current;
              current = root;
      
              if(find(value)){
                  while(current.data != value){
                      if(value < current.data && current.left != null){
                          System.out.println("Node is: "+current.data);
                          current = current.left;
                      }
                      else if(value > current.data && current.right != null){
                          System.out.println("Node is: "+current.data);
                          current = current.right;
                      }                   
                  }
              }
              else
                  System.out.println(value+" Element is not present in tree");
          }
      
          public static void main(String[] args) {
      
              BST b = new BST();
              b.add(50);
              b.add(30);
              b.add(20);
              b.add(40);
              b.add(70);
              b.add(60);
              b.add(80);
              b.add(90);
      
              b.inorder(root);
              b.find(30);
              b.find(90);
              b.find(100);
              b.find(50);
      
              b.successor(90);
              System.out.println();
              b.successor(70);
          }
      
      }
      

    How can I repeat a character in Bash?

    Simplest is to use this one-liner in bash:

    seq 10 | xargs -n 1 | xargs -I {} echo -n  ===\>;echo
    

    VIM Disable Automatic Newline At End Of File

    I have not tried this option, but the following information is given in the vim help system (i.e. help eol):

    'endofline' 'eol'   boolean (default on)
                local to buffer
                {not in Vi}
    
    When writing a file and this option is off and the 'binary' option
    is on, no <EOL> will be written for the last line in the file.  This
    option is automatically set when starting to edit a new file, unless
    the file does not have an <EOL> for the last line in the file, in
    which case it is reset.  
    

    Normally you don't have to set or reset this option. When 'binary' is off the value is not used when writing the file. When 'binary' is on it is used to remember the presence of a for the last line in the file, so that when you write the file the situation from the original file can be kept. But you can change it if you want to.

    You may be interested in the answer to a previous question as well: "Why should files end with a newline".

    How do you return a JSON object from a Java Servlet

    First convert the JSON object to String. Then just write it out to the response writer along with content type of application/json and character encoding of UTF-8.

    Here's an example assuming you're using Google Gson to convert a Java object to a JSON string:

    protected void doXxx(HttpServletRequest request, HttpServletResponse response) {
        // ...
    
        String json = new Gson().toJson(someObject);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
    

    That's all.

    See also:

    forward declaration of a struct in C?

    Try this

    #include <stdio.h>
    
    struct context;
    
    struct funcptrs{
      void (*func0)(struct context *ctx);
      void (*func1)(void);
    };
    
    struct context{
        struct funcptrs fps;
    }; 
    
    void func1 (void) { printf( "1\n" ); }
    void func0 (struct context *ctx) { printf( "0\n" ); }
    
    void getContext(struct context *con){
        con->fps.func0 = func0;  
        con->fps.func1 = func1;  
    }
    
    int main(int argc, char *argv[]){
     struct context c;
       c.fps.func0 = func0;
       c.fps.func1 = func1;
       getContext(&c);
       c.fps.func0(&c);
       getchar();
       return 0;
    }
    

    How to generate random positive and negative numbers in Java

    Generate numbers between 0 and 65535 then just subtract 32768

    Spring - download response as a file

    It is possible to download a file using XHR request. You can use angular $http to load the file and then use Blob feature of HTML5 to make browser save it. There is a library that can help you with saving: FileSaver.js.

    Unexpected token < in first line of HTML

    I had the same issue. I published the angular/core application on iis.

    To change the Identity of the application pool solved my issue. Now the Identity is LocalSystem

    Get an object attribute

    Use getattr if you have an attribute in string form:

    >>> class User(object):
           name = 'John'
    
    >>> u = User()
    >>> param = 'name'
    >>> getattr(u, param)
    'John'
    

    Otherwise use the dot .:

    >>> class User(object):
           name = 'John'
    
    >>> u = User()
    >>> u.name
    'John'
    

    Android: Storing username and password?

    You should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.

    This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.

    SampleSyncAdapter (like @Miguel mentioned) is an example that makes use of stored account credentials.

    Cannot find reference 'xxx' in __init__.py - Python / Pycharm

    You can mark source directory as a source root like so:

    • Right-click on source directory
    • Mark Directory As --> Source Root
    • File --> Invalidate Caches / Restart... -> Invalidate and Restart

    Android Studio is slow (how to speed up)?

    This might sound stupid and off topic but in my case I was using an external 4k Monitor with my MacBook Pro 13' (MacOS High Sierra, 2016) and I had the resolution set to the wrong scaled resolution. Switching to another scaled resolution where there was no "using a scaled resolution may affect performance" warning resolved my overall performance issues. In my case I had to increase the resolution to max.

    So for me it was an overall performance problem which first surfaced with Android Studio, it was not an Android Studio specific problem.

    EDIT 25.11.2017

    As a result I had to increase font sizes in Android Studio:

    enter image description here

    enter image description here

    and on my Mac in General. I followed some of these tips to get that done.

    SQLite Reset Primary Key Field

    Try this:

    delete from your_table;    
    delete from sqlite_sequence where name='your_table';
    

    SQLite Autoincrement

    SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

    Disable Laravel's Eloquent timestamps

    Add this line into your model:

    Overwrite existing variable $timestamps true to false

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    
    public $timestamps = false;
    

    c# datagridview doubleclick on row with FullRowSelect

    Don't manually edit the .designer files in visual studio that usually leads to headaches. Instead either specify it in the properties section of your DataGridRow which should be contained within a DataGrid element. Or if you just want VS to do it for you find the double click event within the properties page->events (little lightning bolt icon) and double click the text area where you would enter a function name for that event.

    This link should help

    http://msdn.microsoft.com/en-us/library/6w2tb12s(v=vs.90).aspx

    error: Your local changes to the following files would be overwritten by checkout

    i had got the same error. Actually i tried to override the flutter Old SDK Package with new Updated Package. so that error occurred.

    i opened flutter sdk directory with VS Code and cleaned the project

    use this code in VSCode cmd

    git clean -dxf

    then use git pull

    this in equals method

    You have to look how this is called:

    someObject.equals(someOtherObj); 

    This invokes the equals method on the instance of someObject. Now, inside that method:

    public boolean equals(Object obj) {   if (obj == this) { //is someObject equal to obj, which in this case is someOtherObj?     return true;//If so, these are the same objects, and return true   } 

    You can see that this is referring to the instance of the object that equals is called on. Note that equals() is non-static, and so must be called only on objects that have been instantiated.

    Note that == is only checking to see if there is referential equality; that is, the reference of this and obj are pointing to the same place in memory. Such references are naturally equal:

    Object a = new Object(); Object b = a; //sets the reference to b to point to the same place as a Object c = a; //same with c b.equals(c);//true, because everything is pointing to the same place 

    Further note that equals() is generally used to also determine value equality. Thus, even if the object references are pointing to different places, it will check the internals to determine if those objects are the same:

    FancyNumber a = new FancyNumber(2);//Internally, I set a field to 2 FancyNumber b = new FancyNumber(2);//Internally, I set a field to 2 a.equals(b);//true, because we define two FancyNumber objects to be equal if their internal field is set to the same thing. 

    Warning about `$HTTP_RAW_POST_DATA` being deprecated

    I experienced the same issue on nginx server (DigitalOcean) - all I had to do is to log in as root and modify the file /etc/php5/fpm/php.ini.

    To find the line with the always_populate_raw_post_data I first run grep:

    grep -n 'always_populate_raw_post_data' php.ini
    

    That returned the line 704

    704:;always_populate_raw_post_data = -1
    

    Then simply open php.ini on that line with vi editor:

    vi +704 php.ini
    

    Remove the semi colon to uncomment it and save the file :wq

    Lastly reboot the server and the error went away.

    How to find whether a ResultSet is empty or not in Java?

    Definitely this gives good solution,

    ResultSet rs = stmt.execute("SQL QUERY");
    // With the above statement you will not have a null ResultSet 'rs'.
    // In case, if any exception occurs then next line of code won't execute.
    // So, no problem if I won't check rs as null.
    
    if (rs.next()) {
        do {
          // Logic to retrieve the data from the resultset.
          // eg: rs.getString("abc");
        } while(rs.next());
    } else {
        // No data
    }
    

    Using the RUN instruction in a Dockerfile with 'source' does not work

    You might want to run bash -v to see what's being sourced.

    I would do the following instead of playing with symlinks:

    RUN echo "source /usr/local/bin/virtualenvwrapper.sh" >> /etc/bash.bashrc

    XAMPP: Couldn't start Apache (Windows 10)

    I found that running apache_start in gave me the exact error and on which line it was.

    My error was that I left a space in between localhost: and the port.

    What's the best way to iterate an Android Cursor?

    import java.util.Iterator;
    import android.database.Cursor;
    
    public class IterableCursor implements Iterable<Cursor>, Iterator<Cursor> {
        Cursor cursor;
        int toVisit;
        public IterableCursor(Cursor cursor) {
            this.cursor = cursor;
            toVisit = cursor.getCount();
        }
        public Iterator<Cursor> iterator() {
            cursor.moveToPosition(-1);
            return this;
        }
        public boolean hasNext() {
            return toVisit>0;
        }
        public Cursor next() {
        //  if (!hasNext()) {
        //      throw new NoSuchElementException();
        //  }
            cursor.moveToNext();
            toVisit--;
            return cursor;
        }
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
    

    Example code:

    static void listAllPhones(Context context) {
        Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        for (Cursor phone : new IterableCursor(phones)) {
            String name = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Log.d("name=" + name + " phoneNumber=" + phoneNumber);
        }
        phones.close();
    }
    

    jQuery position DIV fixed at top on scroll

    instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

    jQuery

      $(window).scroll(function(){
          if ($(this).scrollTop() > 135) {
              $('#task_flyout').addClass('fixed');
          } else {
              $('#task_flyout').removeClass('fixed');
          }
      });
    

    css

    .fixed {position:fixed; top:0; left:0;}
    

    Example

    How do I remove the height style from a DIV using jQuery?

    To reset the height of the div, just try

    $("#someDiv").height('auto');

    SQL Server: how to select records with specific date from datetime column

    The easiest way is to convert to a date:

    SELECT *
    FROM dbo.LogRequests
    WHERE cast(dateX as date) = '2014-05-09';
    

    Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.

    I would be inclined to use the following, just out of habit:

    SELECT *
    FROM dbo.LogRequests
    WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
    

    How do I create a datetime in Python from milliseconds?

    Just convert it to timestamp

    datetime.datetime.fromtimestamp(ms/1000.0)
    

    Good tutorial for using HTML5 History API (Pushstate?)

    You could try Davis.js, it gives you routing in your JavaScript using pushState when available and without JavaScript it allows your server side code to handle the requests.

    How do I see the commit differences between branches in git?

    If you are on Linux, gitg is way to go to do it very quickly and graphically.

    If you insist on command line you can use:

    git log --oneline --decorate
    

    To make git log nicer by default, I typically set these global preferences:

    git config --global log.decorate true
    git config --global log.abbrevCommit true
    

    Using a PHP variable in a text input value = statement

    I have been doing PHP for my project, and I can say that the following code works for me. You should try it.

    echo '<input type = "text" value = '.$idtest.'>'; 
    

    jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

    My favorite no-conflict-friendly construct:

    jQuery(function($) {
      // ...
    });
    

    Calling jQuery with a function pointer is a shortcut for $(document).ready(...)

    Or as we say in coffeescript:

    jQuery ($) ->
      # code here
    

    Decompile Python 2.7 .pyc

    In case anyone is still struggling with this, as I was all morning today, I have found a solution that works for me:

    Uncompyle

    Installation instructions:

    git clone https://github.com/gstarnberger/uncompyle.git
    cd uncompyle/
    sudo ./setup.py install
    

    Once the program is installed (note: it will be installed to your system-wide-accessible Python packages, so it should be in your $PATH), you can recover your Python files like so:

    uncompyler.py thank_goodness_this_still_exists.pyc > recovered_file.py
    

    The decompiler adds some noise mostly in the form of comments, however I've found it to be surprisingly clean and faithful to my original code. You will have to remove a little line of text beginning with +++ near the end of the recovered file to be able to run your code.

    JPA mapping: "QuerySyntaxException: foobar is not mapped..."

    I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation

    The correct format should be

    @Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
    @Table( name = "foobar" ) // Table name 
    public class FooBar{
    

    Why are there no ++ and --? operators in Python?

    Other answers have described why it's not needed for iterators, but sometimes it is useful when assigning to increase a variable in-line, you can achieve the same effect using tuples and multiple assignment:

    b = ++a becomes:

    a,b = (a+1,)*2
    

    and b = a++ becomes:

    a,b = a+1, a
    

    Python 3.8 introduces the assignment := operator, allowing us to achievefoo(++a) with

    foo(a:=a+1)
    

    foo(a++) is still elusive though.

    Get a list of dates between two dates using a function

    This does exactly what you want, modified from Will's earlier post. No need for helper tables or loops.

    WITH date_range (calc_date) AS (
        SELECT DATEADD(DAY, DATEDIFF(DAY, 0, '2010-01-13') - DATEDIFF(DAY, '2010-01-01', '2010-01-13'), 0)
            UNION ALL SELECT DATEADD(DAY, 1, calc_date)
                FROM date_range
                WHERE DATEADD(DAY, 1, calc_date) <= '2010-01-13')
    SELECT calc_date
    FROM date_range;
    

    Shell script to get the process ID on Linux

    If you already know the process then this will be useful:

    PID=`ps -eaf | grep <process> | grep -v grep | awk '{print $2}'`
    if [[ "" !=  "$PID" ]]; then
    echo "killing $PID"
    kill -9 $PID
    fi
    

    Location for session files in Apache/PHP

    If unsure of compiled default for session.save_path, look at the pertinent php.ini.
    Normally, this will show the commented out default value.

    Ubuntu/Debian old/new php.ini locations:
    Older php5 with Apache: /etc/php5/apache2/php.ini
    Older php5 with NGINX+FPM: /etc/php5/fpm/php.ini
    Ubuntu 16+ with Apache: /etc/php/*/apache2/php.ini *
    Ubuntu 16+ with NGINX+FPM - /etc/php/*/fpm/php.ini *

    * /*/ = the current PHP version(s) installed on system.

    To show the PHP version in use under Apache:

    $ a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+"

    7.3

    Since PHP 7.3 is the version running for this example, you would use that for the php.ini:

    $ grep "session.save_path" /etc/php/7.3/apache2/php.ini

    ;session.save_path = "/var/lib/php/sessions"

    Or, combined one-liner:

    $ APACHEPHPVER=$(a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+") \ && grep ";session.save_path" /etc/php/${APACHEPHPVER}/apache2/php.ini

    Result:

    ;session.save_path = "/var/lib/php/sessions"


    Or, use PHP itself to grab the value using the "cli" environment (see NOTE below):

    $ php -r 'echo session_save_path() . "\n";'
    /var/lib/php/sessions
    $
    

    These will also work:

    php -i | grep session.save_path
    
    php -r 'echo phpinfo();' | grep session.save_path
    

    NOTE:

    The 'cli' (command line) version of php.ini normally has the same default values as the Apache2/FPM versions (at least as far as the session.save_path). You could also use a similar command to echo the web server's current PHP module settings to a webpage and use wget/curl to grab the info. There are many posts regarding phpinfo() use in this regard. But, it is quicker to just use the PHP interface or grep for it in the correct php.ini to show it's default value.

    EDIT: Per @aesede comment -> Added php -i. Thanks

    How to enable ASP classic in IIS7.5

    Add Authenticated Users

    Make the file accessible to the Authenticated Users group. Right click your virtual directory and give the group read/write access to Authenticated Users.

    I faced issue on windows 10 machine.

    Date difference in years using C#

    I implemented an extension method to get the number of years between two dates, rounded by whole months.

        /// <summary>
        /// Gets the total number of years between two dates, rounded to whole months.
        /// Examples: 
        /// 2011-12-14, 2012-12-15 returns 1.
        /// 2011-12-14, 2012-12-14 returns 1.
        /// 2011-12-14, 2012-12-13 returns 0,9167.
        /// </summary>
        /// <param name="start">
        /// Stardate of time period
        /// </param>
        /// <param name="end">
        /// Enddate of time period
        /// </param>
        /// <returns>
        /// Total Years between the two days
        /// </returns>
        public static double DifferenceTotalYears(this DateTime start, DateTime end)
        {
            // Get difference in total months.
            int months = ((end.Year - start.Year) * 12) + (end.Month - start.Month);
    
            // substract 1 month if end month is not completed
            if (end.Day < start.Day)
            {
                months--;
            }
    
            double totalyears = months / 12d;
            return totalyears;
        }
    

    How to install .MSI using PowerShell

    In powershell 5.1 you can actually use install-package, but it can't take extra msi arguments.

    install-package .\file.msi
    

    Otherwise with start-process and waiting:

    start -wait file.msi ALLUSERS=1,INSTALLDIR=C:\FILE
    

    Install gitk on Mac

    I had the same problem on Mac 10.7.5 with git version 1.7.12.4

    When I ran gitk I got an error:

    "Error in startup script: expected version number but got "Git-37)"
        while executing
    "package vcompare $git_version "1.6.6.2""
        invoked from within
    "if {[package vcompare $git_version "1.6.6.2"] >= 0} {
        set show_notes "--show-notes"
    }"
        (file "/usr/bin/gitk" line 11587)
    

    When I looked at the code in gitk I saw the line that sets the version.

    set git_version [join [lrange [split [lindex [exec git version] end] .] 0 2] .]
    

    This somehow parsed the git version results to Git-37 instead of 1.7.12.4

    I just replaced the git_version line with:

    set git_version "1.7.12.4"
    

    Proper way to set response status and JSON content in a REST API made with nodejs and express

    You could do it this way:

    res.status(400).json(json_response);
    

    This will set the HTTP status code to 400, it works even in express 4.

    How to pass macro definition from "make" command line arguments (-D) to C source code?

    Call make this way

    make CFLAGS=-Dvar=42
    

    because you do want to override your Makefile's CFLAGS, and not just the environment (which has a lower priority with regard to Makefile variables).

    In HTML5, should the main navigation be inside or outside the <header> element?

    It's a little unclear whether you're asking for opinions, eg. "it's common to do xxx" or an actual rule, so I'm going to lean in the direction of rules.

    The examples you cite seem based upon the examples in the spec for the nav element. Remember that the spec keeps getting tweaked and the rules are sometimes convoluted, so I'd venture many people might tend to just do what's given rather than interpret. You're showing two separate examples with different behavior, so there's only so much you can read into it. Do either of those sites also have the opposing sub/nav situation, and if so how do they handle it?

    Most importantly, though, there's nothing in the spec saying either is the way to do it. One of the goals with HTML5 was to be very clear[this for comparison] about semantics, requirements, etc. so the omission is worth noting. As far as I can see, the examples are independent of each other and equally valid within their own context of layout requirements, etc.

    Having the nav's source position be conditional is kind of silly(another red flag). Just pick a method and go with it.

    Counting the number of files in a directory using Java

    This might not be appropriate for your application, but you could always try a native call (using jni or jna), or exec a platform-specific command and read the output before falling back to list().length. On *nix, you could exec ls -1a | wc -l (note - that's dash-one-a for the first command, and dash-lowercase-L for the second). Not sure what would be right on windows - perhaps just a dir and look for the summary.

    Before bothering with something like this I'd strongly recommend you create a directory with a very large number of files and just see if list().length really does take too long. As this blogger suggests, you may not want to sweat this.

    I'd probably go with Varkhan's answer myself.

    How to run cron once, daily at 10pm

    Here are some more examples

    • Run every 6 hours at 46 mins past the hour:

      46 */6 * * *

    • Run at 2:10 am:

      10 2 * * *

    • Run at 3:15 am:

      15 3 * * *

    • Run at 4:20 am:

      20 4 * * *

    • Run at 5:31 am:

      31 5 * * *

    • Run at 5:31 pm:

      31 17 * * *

    Difference between web server, web container and application server

    Web containers are responsible to provide the run time environment to web applications. It contains components that provide naming context and manages the life cycle of a web application. Web containers are a part of a web server and they generally processes the user request and send a static response.

    Servlet containers are the one where JSP created components reside. They are basically responsible to provide dynamic content as per the user request. Basically, Web containers reply with a static content as per the user request, but Servlets can create the dynamic pages.

    How to convert a factor to integer\numeric without loss of information?

    Note: this particular answer is not for converting numeric-valued factors to numerics, it is for converting categorical factors to their corresponding level numbers.


    Every answer in this post failed to generate results for me , NAs were getting generated.

    y2<-factor(c("A","B","C","D","A")); 
    as.numeric(levels(y2))[y2] 
    [1] NA NA NA NA NA Warning message: NAs introduced by coercion
    

    What worked for me is this -

    as.integer(y2)
    # [1] 1 2 3 4 1
    

    What does the "at" (@) symbol do in Python?

    What does the “at” (@) symbol do in Python?

    @ symbol is a syntactic sugar python provides to utilize decorator,
    to paraphrase the question, It's exactly about what does decorator do in Python?

    Put it simple decorator allow you to modify a given function's definition without touch its innermost (it's closure).
    It's the most case when you import wonderful package from third party. You can visualize it, you can use it, but you cannot touch its innermost and its heart.

    Here is a quick example,
    suppose I define a read_a_book function on Ipython

    In [9]: def read_a_book():
       ...:     return "I am reading the book: "
       ...: 
    In [10]: read_a_book()
    Out[10]: 'I am reading the book: '
    

    You see, I forgot to add a name to it.
    How to solve such a problem? Of course, I could re-define the function as:

    def read_a_book():
        return "I am reading the book: 'Python Cookbook'"
    

    Nevertheless, what if I'm not allowed to manipulate the original function, or if there are thousands of such function to be handled.

    Solve the problem by thinking different and define a new_function

    def add_a_book(func):
        def wrapper():
            return func() + "Python Cookbook"
        return wrapper
    

    Then employ it.

    In [14]: read_a_book = add_a_book(read_a_book)
    In [15]: read_a_book()
    Out[15]: 'I am reading the book: Python Cookbook'
    

    Tada, you see, I amended read_a_book without touching it inner closure. Nothing stops me equipped with decorator.

    What's about @

    @add_a_book
    def read_a_book():
        return "I am reading the book: "
    In [17]: read_a_book()
    Out[17]: 'I am reading the book: Python Cookbook'
    

    @add_a_book is a fancy and handy way to say read_a_book = add_a_book(read_a_book), it's a syntactic sugar, there's nothing more fancier about it.

    Resync git repo with new .gitignore file

    The solution mentioned in ".gitignore file not ignoring" is a bit extreme, but should work:

    # rm all files
    git rm -r --cached .
    # add all files as per new .gitignore
    git add .
    # now, commit for new .gitignore to apply
    git commit -m ".gitignore is now working"
    

    (make sure to commit first your changes you want to keep, to avoid any incident as jball037 comments below.
    The --cached option will keep your files untouched on your disk though.)

    You also have other more fine-grained solution in the blog post "Making Git ignore already-tracked files":

    git rm --cached `git ls-files -i --exclude-standard`
    

    Bassim suggests in his edit:

    Files with space in their paths

    In case you get an error message like fatal: path spec '...' did not match any files, there might be files with spaces in their path.

    You can remove all other files with option --ignore-unmatch:

    git rm --cached --ignore-unmatch `git ls-files -i --exclude-standard`
    

    but unmatched files will remain in your repository and will have to be removed explicitly by enclosing their path with double quotes:

    git rm --cached "<path.to.remaining.file>"
    

    Putting GridView data in a DataTable

    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        DataTable _datatable = new DataTable();
        for (int i = 0; i < grdReport.Columns.Count; i++)
        {
            _datatable.Columns.Add(grdReport.Columns[i].ToString());
        }
        foreach (GridViewRow row in grdReport.Rows)
        {
            DataRow dr = _datatable.NewRow();
            for (int j = 0; j < grdReport.Columns.Count; j++)
            {
                if (!row.Cells[j].Text.Equals("&nbsp;"))
                    dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
            }
    
            _datatable.Rows.Add(dr);
        }
        ExportDataTableToExcel(_datatable);
    }
    

    SQL query return data from multiple tables

    Ok, I found this post very interesting and I would like to share some of my knowledge on creating a query. Thanks for this Fluffeh. Others who may read this and may feel that I'm wrong are 101% free to edit and criticise my answer. (Honestly, I feel very thankful for correcting my mistake(s).)

    I'll be posting some of the frequently asked questions in MySQL tag.


    Trick No. 1 (rows that matches to multiple conditions)

    Given this schema

    CREATE TABLE MovieList
    (
        ID INT,
        MovieName VARCHAR(25),
        CONSTRAINT ml_pk PRIMARY KEY (ID),
        CONSTRAINT ml_uq UNIQUE (MovieName)
    );
    
    INSERT INTO MovieList VALUES (1, 'American Pie');
    INSERT INTO MovieList VALUES (2, 'The Notebook');
    INSERT INTO MovieList VALUES (3, 'Discovery Channel: Africa');
    INSERT INTO MovieList VALUES (4, 'Mr. Bean');
    INSERT INTO MovieList VALUES (5, 'Expendables 2');
    
    CREATE TABLE CategoryList
    (
        MovieID INT,
        CategoryName VARCHAR(25),
        CONSTRAINT cl_uq UNIQUE(MovieID, CategoryName),
        CONSTRAINT cl_fk FOREIGN KEY (MovieID) REFERENCES MovieList(ID)
    );
    
    INSERT INTO CategoryList VALUES (1, 'Comedy');
    INSERT INTO CategoryList VALUES (1, 'Romance');
    INSERT INTO CategoryList VALUES (2, 'Romance');
    INSERT INTO CategoryList VALUES (2, 'Drama');
    INSERT INTO CategoryList VALUES (3, 'Documentary');
    INSERT INTO CategoryList VALUES (4, 'Comedy');
    INSERT INTO CategoryList VALUES (5, 'Comedy');
    INSERT INTO CategoryList VALUES (5, 'Action');
    

    QUESTION

    Find all movies that belong to at least both Comedy and Romance categories.

    Solution

    This question can be very tricky sometimes. It may seem that a query like this will be the answer:-

    SELECT  DISTINCT a.MovieName
    FROM    MovieList a
            INNER JOIN CategoryList b
                ON a.ID = b.MovieID
    WHERE   b.CategoryName = 'Comedy' AND
            b.CategoryName = 'Romance'
    

    SQLFiddle Demo

    which is definitely very wrong because it produces no result. The explanation of this is that there is only one valid value of CategoryName on each row. For instance, the first condition returns true, the second condition is always false. Thus, by using AND operator, both condition should be true; otherwise, it will be false. Another query is like this,

    SELECT  DISTINCT a.MovieName
    FROM    MovieList a
            INNER JOIN CategoryList b
                ON a.ID = b.MovieID
    WHERE   b.CategoryName IN ('Comedy','Romance')
    

    SQLFiddle Demo

    and the result is still incorrect because it matches to record that has at least one match on the categoryName. The real solution would be by counting the number of record instances per movie. The number of instance should match to the total number of the values supplied in the condition.

    SELECT  a.MovieName
    FROM    MovieList a
            INNER JOIN CategoryList b
                ON a.ID = b.MovieID
    WHERE   b.CategoryName IN ('Comedy','Romance')
    GROUP BY a.MovieName
    HAVING COUNT(*) = 2
    

    SQLFiddle Demo (the answer)


    Trick No. 2 (maximum record for each entry)

    Given schema,

    CREATE TABLE Software
    (
        ID INT,
        SoftwareName VARCHAR(25),
        Descriptions VARCHAR(150),
        CONSTRAINT sw_pk PRIMARY KEY (ID),
        CONSTRAINT sw_uq UNIQUE (SoftwareName)  
    );
    
    INSERT INTO Software VALUES (1,'PaintMe','used for photo editing');
    INSERT INTO Software VALUES (2,'World Map','contains map of different places of the world');
    INSERT INTO Software VALUES (3,'Dictionary','contains description, synonym, antonym of the words');
    
    CREATE TABLE VersionList
    (
        SoftwareID INT,
        VersionNo INT,
        DateReleased DATE,
        CONSTRAINT sw_uq UNIQUE (SoftwareID, VersionNo),
        CONSTRAINT sw_fk FOREIGN KEY (SOftwareID) REFERENCES Software(ID)
    );
    
    INSERT INTO VersionList VALUES (3, 2, '2009-12-01');
    INSERT INTO VersionList VALUES (3, 1, '2009-11-01');
    INSERT INTO VersionList VALUES (3, 3, '2010-01-01');
    INSERT INTO VersionList VALUES (2, 2, '2010-12-01');
    INSERT INTO VersionList VALUES (2, 1, '2009-12-01');
    INSERT INTO VersionList VALUES (1, 3, '2011-12-01');
    INSERT INTO VersionList VALUES (1, 2, '2010-12-01');
    INSERT INTO VersionList VALUES (1, 1, '2009-12-01');
    INSERT INTO VersionList VALUES (1, 4, '2012-12-01');
    

    QUESTION

    Find the latest version on each software. Display the following columns: SoftwareName,Descriptions,LatestVersion (from VersionNo column),DateReleased

    Solution

    Some SQL developers mistakenly use MAX() aggregate function. They tend to create like this,

    SELECT  a.SoftwareName, a.Descriptions,
            MAX(b.VersionNo) AS LatestVersion, b.DateReleased
    FROM    Software a
            INNER JOIN VersionList b
                ON a.ID = b.SoftwareID
    GROUP BY a.ID
    ORDER BY a.ID
    

    SQLFiddle Demo

    (most RDBMS generates a syntax error on this because of not specifying some of the non-aggregated columns on the group by clause) the result produces the correct LatestVersion on each software but obviously the DateReleased are incorrect. MySQL doesn't support Window Functions and Common Table Expression yet as some RDBMS do already. The workaround on this problem is to create a subquery which gets the individual maximum versionNo on each software and later on be joined on the other tables.

    SELECT  a.SoftwareName, a.Descriptions,
            b.LatestVersion, c.DateReleased
    FROM    Software a
            INNER JOIN
            (
                SELECT  SoftwareID, MAX(VersionNO) LatestVersion
                FROM    VersionList
                GROUP BY SoftwareID
            ) b ON a.ID = b.SoftwareID
            INNER JOIN VersionList c
                ON  c.SoftwareID = b.SoftwareID AND
                    c.VersionNO = b.LatestVersion
    GROUP BY a.ID
    ORDER BY a.ID
    

    SQLFiddle Demo (the answer)


    So that was it. I'll be posting another soon as I recall any other FAQ on MySQL tag. Thank you for reading this little article. I hope that you have atleast get even a little knowledge from this.

    UPDATE 1


    Trick No. 3 (Finding the latest record between two IDs)

    Given Schema

    CREATE TABLE userList
    (
        ID INT,
        NAME VARCHAR(20),
        CONSTRAINT us_pk PRIMARY KEY (ID),
        CONSTRAINT us_uq UNIQUE (NAME)  
    );
    
    INSERT INTO userList VALUES (1, 'Fluffeh');
    INSERT INTO userList VALUES (2, 'John Woo');
    INSERT INTO userList VALUES (3, 'hims056');
    
    CREATE TABLE CONVERSATION
    (
        ID INT,
        FROM_ID INT,
        TO_ID INT,
        MESSAGE VARCHAR(250),
        DeliveryDate DATE
    );
    
    INSERT INTO CONVERSATION VALUES (1, 1, 2, 'hi john', '2012-01-01');
    INSERT INTO CONVERSATION VALUES (2, 2, 1, 'hello fluff', '2012-01-02');
    INSERT INTO CONVERSATION VALUES (3, 1, 3, 'hey hims', '2012-01-03');
    INSERT INTO CONVERSATION VALUES (4, 1, 3, 'please reply', '2012-01-04');
    INSERT INTO CONVERSATION VALUES (5, 3, 1, 'how are you?', '2012-01-05');
    INSERT INTO CONVERSATION VALUES (6, 3, 2, 'sample message!', '2012-01-05');
    

    QUESTION

    Find the latest conversation between two users.

    Solution

    SELECT    b.Name SenderName,
              c.Name RecipientName,
              a.Message,
              a.DeliveryDate
    FROM      Conversation a
              INNER JOIN userList b
                ON a.From_ID = b.ID
              INNER JOIN userList c
                ON a.To_ID = c.ID
    WHERE     (LEAST(a.FROM_ID, a.TO_ID), GREATEST(a.FROM_ID, a.TO_ID), DeliveryDate)
    IN
    (
        SELECT  LEAST(FROM_ID, TO_ID) minFROM,
                GREATEST(FROM_ID, TO_ID) maxTo,
                MAX(DeliveryDate) maxDate
        FROM    Conversation
        GROUP BY minFROM, maxTo
    )
    

    SQLFiddle Demo

    Convert one date format into another in PHP

    Try this:

    $old_date = date('y-m-d-h-i-s');
    $new_date = date('Y-m-d H:i:s', strtotime($old_date));
    

    Wait Until File Is Completely Written

    When the file is writing in binary(byte by byte),create FileStream and above solutions Not working,because file is ready and wrotted in every bytes,so in this Situation you need other workaround like this: Do this when file created or you want to start processing on file

    long fileSize = 0;
    currentFile = new FileInfo(path);
    
    while (fileSize < currentFile.Length)//check size is stable or increased
    {
      fileSize = currentFile.Length;//get current size
      System.Threading.Thread.Sleep(500);//wait a moment for processing copy
      currentFile.Refresh();//refresh length value
    }
    
    //Now file is ready for any process!
    

    Getting a directory name from a filename

    I'm so surprised no one has mentioned the standard way in Posix

    Please use basename / dirname constructs.

    man basename

    C++ Dynamic Shared Library on Linux

    Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library

    Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.

    If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.

    How to reset a form using jQuery with .reset() method

    Here is simple solution with Jquery. It works globally. Have a look on the code.

    $('document').on("click", ".clear", function(){
       $(this).closest('form').trigger("reset");
    })
    

    Add a clear class to a button in every form you need to reset it. For example:

    <button class="button clear" type="reset">Clear</button>
    

    Pandas: sum DataFrame rows for given columns

    This is a simpler way using iloc to select which columns to sum:

    df['f']=df.iloc[:,0:2].sum(axis=1)
    df['g']=df.iloc[:,[0,1]].sum(axis=1)
    df['h']=df.iloc[:,[0,3]].sum(axis=1)
    

    Produces:

       a  b   c  d   e  f  g   h
    0  1  2  dd  5   8  3  3   6
    1  2  3  ee  9  14  5  5  11
    2  3  4  ff  1   8  7  7   4
    

    I can't find a way to combine a range and specific columns that works e.g. something like:

    df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
    df['i']=df.iloc[:,[0:2,3]].sum(axis=1)
    

    How to create a GUID / UUID

    There are many correct answers here, but sadly, included code samples are quite cryptic and difficult to understand. This is how I create version 4 (random) UUIDs.

    Note that following pieces of code make use of binary literals for improved readability, thus require ECMAScript 6.

    Node version

    function uuid4() {
      let array = new Uint8Array(16)
      crypto.randomFillSync(array)
    
      // manipulate 9th byte
      array[8] &= 0b00111111 // clear first two bits
      array[8] |= 0b10000000 // set first two bits to 10
    
      // manipulate 7th byte
      array[6] &= 0b00001111 // clear first four bits
      array[6] |= 0b01000000 // set first four bits to 0100
    
      const pattern = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
      let idx = 0
    
      return pattern.replace(
        /XX/g,
        () => array[idx++].toString(16).padStart(2, "0"), // padStart ensures leading zero, if needed
      )
    }
    

    Browser version

    Only the 2nd line is different.

    function uuid4() {
      let array = new Uint8Array(16)
      crypto.getRandomValues(array)
    
      // manipulate 9th byte
      array[8] &= 0b00111111 // clear first two bits
      array[8] |= 0b10000000 // set first two bits to 10
    
      // manipulate 7th byte
      array[6] &= 0b00001111 // clear first four bits
      array[6] |= 0b01000000 // set first four bits to 0100
    
      const pattern = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
      let idx = 0
    
      return pattern.replace(
        /XX/g,
        () => array[idx++].toString(16).padStart(2, "0"), // padStart ensures leading zero, if needed
      )
    }
    

    Tests

    And finally, corresponding tests (Jasmine).

    describe(".uuid4()", function() {
      it("returns a UUIDv4 string", function() {
        const uuidPattern = "XXXXXXXX-XXXX-4XXX-YXXX-XXXXXXXXXXXX"
        const uuidPatternRx = new RegExp(uuidPattern.
          replaceAll("X", "[0-9a-f]").
          replaceAll("Y", "[89ab]"))
    
        for (let attempt = 0; attempt < 1000; attempt++) {
          let retval = uuid4()
          expect(retval.length).toEqual(36)
          expect(retval).toMatch(uuidPatternRx)
        }
      })
    })
    

    UUID v4 explained

    A very good explanation of UUID version 4 is here: https://www.cryptosys.net/pki/uuid-rfc4122.html.

    Final notes

    Also, there are plenty of third-party packages. However, as long as you have just basic needs, I don't recommend them. Really, there is not much to win and pretty much to lose. Authors may pursue for tiniest bits of performance, "fix" things which aren't supposed to be fixed, and when it comes to security, it is a risky idea. Similarly, they may introduce other bugs or incompatibilities. Careful updates require time.

    How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

    You can cast it to

    (<any>$('.selector') ).function();
    

    Ex: date picker initialize using jquery

    (<any>$('.datepicker') ).datepicker();
    

    How to get size of mysql database?

    Alternatively, if you are using phpMyAdmin, you can take a look at the sum of the table sizes in the footer of your database structure tab. The actual database size may be slightly over this size, however it appears to be consistent with the table_schema method mentioned above.

    Screen-shot :

    enter image description here

    Adding a new SQL column with a default value

    This will work for ENUM type as default value

    ALTER TABLE engagete_st.holidays add column `STATUS` ENUM('A', 'D') default 'A' AFTER `H_TYPE`;
    

    Fixed positioning in Mobile Safari

    Our web app requires a fixed header. We are fortunate in that we only have to support the latest browsers, but Safari's behavior in this area caused us a real problem.

    The best fix, as others have pointed out, is to write our own scrolling code. However, we can't justify that effort to fix a problem that occurs only on iOS. It makes more sense to hope that Apple may fix this problem, especially since, as QuirksMode suggests, Apple now stands alone in their interpretation of "position:fixed".

    http://www.quirksmode.org/blog/archives/2013/12/position_fixed_1.html

    What worked for us is to toggle between "position:fixed" and "position:absolute" depending on whether the user has zoomed. This replaces our "floating" header with predictable behavior, which is important for usability. When zoomed, the behavior is not what we want, but the user can easily work around this by reversing the zoom.

    // On iOS, "position: fixed;" is not supported when zoomed, so toggle "position: absolute;".
    header = document.createElement( "HEADER" );
    document.body.appendChild( header );
    if( navigator.userAgent.match( /iPad/i ) || navigator.userAgent.match( /iPhone/i )) {
        addEventListener( document.body, function( event ) {
            var zoomLevel = (( Math.abs( window.orientation ) === 90 ) ? screen.height : screen.width ) / window.innerWidth;
            header.style.position = ( zoomLevel > 1 ) ? "absolute" : "fixed";
        });
    }
    

    How to analyze information from a Java core dump?

    I recommend you to try Netbeans Profiler.It has rich set of tools for real time analysis. Tools from IbM are worth a try for offline analysis

    What is the best/simplest way to read in an XML file in Java application?

    The simplest by far will be Simple http://simple.sourceforge.net, you only need to annotate a single object like so

    @Root
    public class Entry {
    
       @Attribute
       private String a
       @Attribute
       private int b;
       @Element
       private Date c;
    
       public String getSomething() {
          return a;
       }
    } 
    
    @Root
    public class Configuration {
    
       @ElementList(inline=true)
       private List<Entry> entries;
    
       public List<Entry> getEntries() { 
          return entries;
       }
    }
    

    Then all you have to do to read the whole file is specify the location and it will parse and populate the annotated POJO's. This will do all the type conversions and validation. You can also annotate for persister callbacks if required. Reading it can be done like so.

    Serializer serializer = new Persister();
    Configuration configuraiton = serializer.read(Configuration.class, fileLocation);
    

    Does functional programming replace GoF design patterns?

    I think that each paradigm serves a different purpose and as such cannot be compared in this way.

    I have not heard that the GoF design patterns are applicable to every language. I have heard that they are applicable to all OOP languages. If you use functional programming then the domain of problems that you solve is different from OO languages.

    I wouldn't use functional language to write a user interface, but one of the OO languages like C# or Java would make this job easier. If I were writing a functional language then I wouldn't consider using OO design patterns.

    Converting String to Cstring in C++

    vector<char> toVector( const std::string& s ) {
      string s = "apple";  
      vector<char> v(s.size()+1);
      memcpy( &v.front(), s.c_str(), s.size() + 1 );
      return v;
    }
    vector<char> v = toVector(std::string("apple"));
    
    // what you were looking for (mutable)
    char* c = v.data();
    

    .c_str() works for immutable. The vector will manage the memory for you.

    Ctrl+click doesn't work in Eclipse Juno

    I faced this issue several times. As described by Ashutosh Jindal, if the Hyperlinking is already enabled and still the ctrl+click doesn't work then you need to:

    1. Navigate to Java -> Editor -> Mark Occurrences in Preferences
    2. Uncheck "Mark occurrences of the selected element in the current file" if its already checked.
    3. Now, check on the above mentioned option and then check on all the items under it. Click Apply.

    This should now enabled the ctrl+click functionality.

    MD5 hashing in Android

    If using Apache Commons Codec is an option, then this would be a shorter implementation:

    String md5Hex = new String(Hex.encodeHex(DigestUtils.md5(data)));
    

    Or SHA:

    String shaHex= new String(Hex.encodeHex(DigestUtils.sha("textToHash")));
    

    Source for above.

    Please follow the link and upvote his solution to award the correct person.


    Maven repo link: https://mvnrepository.com/artifact/commons-codec/commons-codec

    Current Maven dependency (as of 6 July 2016):

    <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>
    

    How best to include other scripts?

    Most of the answers I saw here seem to overcomplicate things. This method has always worked reliably for me:

    FULLPATH=$(readlink -f $0)
    INCPATH=${FULLPATH%/*}
    

    INCPATH will hold the complete path of the script excluding the script filename, regardless of how the script is called (by $PATH, relative or absolute).

    After that, one only needs to do this to include files in the same directory:

    . $INCPATH/file_to_include.sh
    

    Reference: TecPorto / Location independent includes

    Difference between jar and war in Java

    JAR files allow to package multiple files in order to use it as a library, plugin, or any kind of application. On the other hand, WAR files are used only for web applications.

    JAR can be created with any desired structure. In contrast, WAR has a predefined structure with WEB-INF and META-INF directories.

    A JAR file allows Java Runtime Environment (JRE) to deploy an entire application including the classes and the associated resources in a single request. On the other hand, a WAR file allows testing and deploying a web application easily.

    Change CSS class properties with jQuery

    You can remove classes and add classes dynamically

    $(document).ready(function(){
        $('#div').removeClass('left').addClass('right');
    });
    

    What is the most "pythonic" way to iterate over a list in chunks?

    Unless I misses something, the following simple solution with generator expressions has not been mentioned. It assumes that both the size and the number of chunks are known (which is often the case), and that no padding is required:

    def chunks(it, n, m):
        """Make an iterator over m first chunks of size n.
        """
        it = iter(it)
        # Chunks are presented as tuples.
        return (tuple(next(it) for _ in range(n)) for _ in range(m))
    

    Format output string, right alignment

    Try this approach using the newer str.format syntax:

    line_new = '{:>12}  {:>12}  {:>12}'.format(word[0], word[1], word[2])
    

    And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):

    line_new = '%12s  %12s  %12s' % (word[0], word[1], word[2])
    

    Renaming files in a folder to sequential numbers

    If your rename doesn't support -N, you can do something like this:

    ls -1 --color=never -c | xargs rename -n 's/.*/our $i; sprintf("%04d.jpg", $i++)/e'
    

    Edit To start with a given number, you can use the (somewhat ugly-looking) code below, just replace 123 with the number you want:

    ls -1 --color=never  -c | xargs rename -n 's/.*/our $i; if(!$i) { $i=123; } sprintf("%04d.jpg", $i++)/e'
    

    This lists files in order by creation time (newest first, add -r to ls to reverse sort), then sends this list of files to rename. Rename uses perl code in the regex to format and increment counter.

    However, if you're dealing with JPEG images with EXIF information, I'd recommend exiftool

    This is from the exiftool documentation, under "Renaming Examples"

       exiftool '-FileName<CreateDate' -d %Y%m%d_%H%M%S%%-c.%%e dir
    
       Rename all images in "dir" according to the "CreateDate" date and time, adding a copy number with leading '-' if the file already exists ("%-c"), and
       preserving the original file extension (%e).  Note the extra '%' necessary to escape the filename codes (%c and %e) in the date format string.
    

    Best way to get identity of inserted row?

    @@IDENTITY is the last identity inserted using the current SQL Connection. This is a good value to return from an insert stored procedure, where you just need the identity inserted for your new record, and don't care if more rows were added afterward.

    SCOPE_IDENTITY is the last identity inserted using the current SQL Connection, and in the current scope -- that is, if there was a second IDENTITY inserted based on a trigger after your insert, it would not be reflected in SCOPE_IDENTITY, only the insert you performed. Frankly, I have never had a reason to use this.

    IDENT_CURRENT(tablename) is the last identity inserted regardless of connection or scope. You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into.

    Testing if a site is vulnerable to Sql Injection

    SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.

    First rule of securing any script or page that attaches to a database instance is Do not trust user input.

    Your example is attempting to end a misquoted string in an SQL statement. To understand this, you first need to understand SQL statements. In your example of adding a ' to a paramater, your 'injection' is hoping for the following type of statement:

    SELECT username,password FROM users WHERE username='$username'

    By appending a ' to that statement, you could then add additional SQL paramaters or queries.: ' OR username --

    SELECT username,password FROM users WHERE username='' OR username -- '$username

    That is an injection (one type of; Query Reshaping). The user input becomes an injected statement into the pre-written SQL statement.

    Generally there are three types of SQL injection methods:

    • Query Reshaping or redirection (above)
    • Error message based (No such user/password)
    • Blind Injections

    Read up on SQL Injection, How to test for vulnerabilities, understanding and overcoming SQL injection, and this question (and related ones) on StackOverflow about avoiding injections.

    Edit:

    As far as TESTING your site for SQL injection, understand it gets A LOT more complex than just 'append a symbol'. If your site is critical, and you (or your company) can afford it, hire a professional pen tester. Failing that, this great exaxmple/proof can show you some common techniques one might use to perform an injection test. There is also SQLMap which can automate some tests for SQL Injection and database take over scenarios.

    #define macro for debug printing in C?

    For a portable (ISO C90) implementation, you could use double parentheses, like this;

    #include <stdio.h>
    #include <stdarg.h>
    
    #ifndef NDEBUG
    #  define debug_print(msg) stderr_printf msg
    #else
    #  define debug_print(msg) (void)0
    #endif
    
    void
    stderr_printf(const char *fmt, ...)
    {
      va_list ap;
      va_start(ap, fmt);
      vfprintf(stderr, fmt, ap);
      va_end(ap);
    }
    
    int
    main(int argc, char *argv[])
    {
      debug_print(("argv[0] is %s, argc is %d\n", argv[0], argc));
      return 0;
    }
    

    or (hackish, wouldn't recommend it)

    #include <stdio.h>
    
    #define _ ,
    #ifndef NDEBUG
    #  define debug_print(msg) fprintf(stderr, msg)
    #else
    #  define debug_print(msg) (void)0
    #endif
    
    int
    main(int argc, char *argv[])
    {
      debug_print("argv[0] is %s, argc is %d"_ argv[0] _ argc);
      return 0;
    }
    

    How to get an Android WakeLock to work?

    Add permission in AndroidManifest.xml:

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    

    Then add code in my.xml:

    android:keepScreenOn="true"
    

    in this case will never turn off the page! You can read more this

    Check if a input box is empty

    To auto check a checkbox if input field is not empty.

     <md-content>
                <md-checkbox ng-checked="myField.length"> Other </md-checkbox>
                <input  ng-model="myField" placeholder="Please Specify" type="text">
     </md-content>
    

    How to Get the HTTP Post data in C#?

    Try this

    string[] keys = Request.Form.AllKeys;
    var value = "";
    for (int i= 0; i < keys.Length; i++) 
    {
       // here you get the name eg test[0].quantity
       // keys[i];
       // to get the value you use
       value = Request.Form[keys[i]];
    }
    

    How to generate auto increment field in select query

    here's for SQL server, Oracle, PostgreSQL which support window functions.

    SELECT  ROW_NUMBER() OVER (ORDER BY first_name, last_name)  Sequence_no,
            first_name,
            last_name
    FROM    tableName
    

    How to run only one task in ansible playbook?

    There is a way, although not very elegant:

    1. ansible-playbook roles/hadoop_primary/tasks/hadoop_master.yml --step --start-at-task='start hadoop jobtracker services'
    2. You will get a prompt: Perform task: start hadoop jobtracker services (y/n/c)
    3. Answer y
    4. You will get a next prompt, press Ctrl-C

    How do I find a default constraint using INFORMATION_SCHEMA?

    How about using a combination of CHECK_CONSTRAINTS and CONSTRAINT_COLUMN_USAGE:

        select columns.table_name,columns.column_name,columns.column_default,checks.constraint_name
              from information_schema.columns columns
                 inner join information_schema.constraint_column_usage usage on 
                      columns.column_name = usage.column_name and columns.table_name = usage.table_name
                 inner join information_schema.check_constraints checks on usage.constraint_name = checks.constraint_name
        where columns.column_default is not null
    

    How to create a numpy array of all True or all False?

    Quickly ran a timeit to see, if there are any differences between the np.full and np.ones version.

    Answer: No

    import timeit
    
    n_array, n_test = 1000, 10000
    setup = f"import numpy as np; n = {n_array};"
    
    print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s")
    print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")
    

    Result:

    np.ones: 0.38416870904620737s
    np.full: 0.38430388597771525s
    


    IMPORTANT

    Regarding the post about np.empty (and I cannot comment, as my reputation is too low):

    DON'T DO THAT. DON'T USE np.empty to initialize an all-True array

    As the array is empty, the memory is not written and there is no guarantee, what your values will be, e.g.

    >>> print(np.empty((4,4), dtype=bool))
    [[ True  True  True  True]
     [ True  True  True  True]
     [ True  True  True  True]
     [ True  True False False]]
    

    T-test in Pandas

    it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as:

    from scipy.stats import ttest_ind
    
    cat1 = my_data[my_data['Category']=='cat1']
    cat2 = my_data[my_data['Category']=='cat2']
    
    ttest_ind(cat1['values'], cat2['values'])
    >>> (1.4927289925706944, 0.16970867501294376)
    

    it returns a tuple with the t-statistic & the p-value

    see here for other t-tests http://docs.scipy.org/doc/scipy/reference/stats.html

    Find out who is locking a file on a network share

    Just in case someone looking for a solution to this for a Windows based system or NAS:

    There is a built-in function in Windows that shows you what files on the local computer are open/locked by remote computer (which has the file open through a file share):

    • Select "Manage Computer" (Open "Computer Management")
    • click "Shared Folders"
    • choose "Open Files"

    There you can even close the file forcefully.

    MySQL SELECT query string matching

    You can use regular expressions like this:

    SELECT * FROM pet WHERE name REGEXP 'Bob|Smith'; 
    

    ModuleNotFoundError: No module named 'sklearn'


    Brief Introduction


    When using Anaconda, one needs to be aware of the environment that one is working.

    Then, in Anaconda Prompt (base) one needs to use the following code:

    conda $command -n $ENVIRONMENT_NAME $IDE/package/module
    

    $command - Command that I intend to use (consult documentation for general commands)

    $ENVIRONMENT NAME - The name of your environment (if one is working in the root, conda $command $IDE/package/module is enough)

    $IDE/package/module - The name of the IDE or package or module


    Solution


    If one wants to install it in the root and one follows the requirements - (Python (>= 2.7 or >= 3.4), NumPy (>= 1.8.2), SciPy (>= 0.13.3).) - the following will solve the problem:

    conda install scikit-learn
    

    Let's say that one is working in the environment with the name ML.

    Then the following will solve one's problem:

    conda install -n ML scikit-learn
    

    Note: If one needs to install/update packages, the logic is the same as mentioned in the introduction. If you need more information on Anaconda Packages, check the documentation.


    If the above doesn't work, on Anaconda Prompt one can also use pip (here's how to pip install scikit-learn) so the following may help

    pip install scikit-learn
    

    List an Array of Strings in alphabetical order

    You can use Arrays.sort() method. Here's the example,

    import java.util.Arrays;
    
    public class Test 
    {
        public static void main(String[] args) 
        {
            String arrString[] = { "peter", "taylor", "brooke", "frederick", "cameron" };
            orderedGuests(arrString);
        }
    
        public static void orderedGuests(String[] hotel)
        {
            Arrays.sort(hotel);
            System.out.println(Arrays.toString(hotel));
        }
    }
    

    Output

    [brooke, cameron, frederick, peter, taylor]

    grant remote access of MySQL database from any IP address

    If you want to grant remote access of your database from any IP address, run the mysql command and after that run the following command.

    GRANT ALL PRIVILEGES ON *.*
    TO 'root'@'%' 
    IDENTIFIED BY 'password' 
    WITH GRANT OPTION;
    

    Pressing Ctrl + A in Selenium WebDriver

    In Selenium for C#, sending Keys.Control simply toggles the Control key's state: if it's up, then it becomes down; if it's down, then it becomes up. So to simulate pressing Control+A, send Keys.Control twice, once before sending "a" and then after.

    For example, if we is an input IWebElement, the following statement will select all of its contents:

    we.SendKeys(Keys.Control + "a" + Keys.Control);

    Address already in use: JVM_Bind java

    This recently happen to me when enabling JMX on two running tomcat service within Eclipse. I mistakenly put the same port for each server.

    Simply give each jmx remote a different port

    Server 1

    -Dcom.sun.management.jmxremote.port=9000
    

    Server 2

    -Dcom.sun.management.jmxremote.port=9001
    

    How can I use the apply() function for a single column?

    If you are really concerned about the execution speed of your apply function and you have a huge dataset to work on, you could use swifter to make faster execution, here is an example for swifter on pandas dataframe:

    import pandas as pd
    import swifter
    
    def fnc(m):
        return m*3+4
    
    df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})
    
    # apply a self created function to a single column in pandas
    df["y"] = df.m.swifter.apply(fnc)
    

    This will enable your all CPU cores to compute the result hence it will be much faster than normal apply functions. Try and let me know if it become useful for you.

    How can I render a list select box (dropdown) with bootstrap?

    Another way without using the .form-control is this:

      $(".dropdown-menu li a").click(function(){
            $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');
            $(this).parents(".btn-group").find('.btn').val($(this).data('value'));
          });
    

    _x000D_
    _x000D_
    $(".dropdown-menu li a").click(function(){_x000D_
      $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');_x000D_
      $(this).parents(".btn-group").find('.btn').val($(this).data('value'));_x000D_
    });
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
    _x000D_
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
    _x000D_
    _x000D_
    <div class="btn-group">_x000D_
      <button  type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
                      Test <span class="caret"> </span>_x000D_
      </button>_x000D_
      <ul class="dropdown-menu">_x000D_
        <li><a href='#'>test 1</a></li>_x000D_
        <li><a href='#'>test 2</a></li>_x000D_
        <li><a href='#'>test 3</a></li>_x000D_
      </ul>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to mark-up phone numbers?

    Mobile Safari (iPhone & iPod Touch) use the tel: scheme.

    How do I dial a phone number from a webpage on iPhone?

    How can I start an Activity from a non-Activity class?

    Once you have obtained the context in your onTap() you can also do:

    Intent myIntent = new Intent(mContext, theNewActivity.class);
    mContext.startActivity(myIntent);
    

    MongoDB Aggregation: How to get total records count?

    If you don't want to group, then use the following method:

    db.collection.aggregate( [ { $match : { score : { $gt : 70, $lte : 90 } } }, { $count: 'count' } ] );

    Equivalent VB keyword for 'break'

    Exit [construct], and intelisense will tell you which one(s) are valid in a particular place.

    How to round each item in a list of floats to 2 decimal places?

    You can use the built-in map along with a lambda expression:

    my_list = [0.2111111111, 0.5, 0.3777777777]
    my_list_rounded = list(map(lambda x: round(x, ndigits=2), my_list))
    my_list_rounded                                                                                                                                                                                                                 
    Out[3]: [0.21, 0.5, 0.38]
    

    Alternatively you could also create a named function for the rounding up to a specific digit using partial from the functools module for working with higher order functions:

    from functools import partial
    
    my_list = [0.2111111111, 0.5, 0.3777777777]
    round_2digits = partial(round, ndigits=2)
    my_list_rounded = list(map(round_2digits, my_list))
    my_list_rounded                                                                                                                                                                                                                 
    Out[6]: [0.21, 0.5, 0.38]
    

    How can foreign key constraints be temporarily disabled using T-SQL?

    The SQL-92 standard allows for a constaint to be declared as DEFERRABLE so that it can be deferred (implicitly or explicitly) within the scope of a transaction. Sadly, SQL Server is still missing this SQL-92 functionality.

    For me, changing a constraint to NOCHECK is akin to changing the database structure on the fly -- dropping constraints certainly is -- and something to be avoided (e.g. users require increased privileges).

    Cannot invoke an expression whose type lacks a call signature

    Perhaps create a shared Fruit interface that provides isDecayed. fruits is now of type Fruit[] so the type can be explicit. Like this:

    interface Fruit {
        isDecayed: boolean;
    }
    
    interface Apple extends Fruit {
        color: string;
    }
    
    interface Pear extends Fruit {
        weight: number;
    }
    
    interface FruitBasket {
        apples: Apple[];
        pears: Pear[];
    }
    
    
    const fruitBasket: FruitBasket = { apples: [], pears: [] };
    const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears'; 
    const fruits: Fruit[] = fruitBasket[key];
    
    const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);
    

    XDocument or XmlDocument

    I believe that XDocument makes a lot more object creation calls. I suspect that for when you're handling a lot of XML documents, XMLDocument will be faster.

    One place this happens is in managing scan data. Many scan tools output their data in XML (for obvious reasons). If you have to process a lot of these scan files, I think you'll have better performance with XMLDocument.

    How to pass parameters to maven build using pom.xml?

    If we have parameter like below in our POM XML

    <version>${project.version}.${svn.version}</version>
      <packaging>war</packaging>
    

    I run maven command line as follows :

    mvn clean install package -Dproject.version=10 -Dsvn.version=1
    

    SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

    SELECT COLUMN 
        FROM TABLE 
    WHERE columns_name
        IN ( SELECT COLUMN FROM TABLE WHERE columns_name = 'value');
    

    note: when we are using sub-query we must focus on these points:

    1. if our sub query returns 1 value in this case we need to use (=,!=,<>,<,>....)
    2. else (more than one value), in this case we need to use (in, any, all, some )

    The module ".dll" was loaded but the entry-point was not found

    The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
    From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

    Determine which MySQL configuration file is being used

    For people running windows server with mysql as a service, an easy way to find out what config file you are running is to open up the services control panel, find your mysql service (in my case 'MYSQL56'), right click and click properties. Then from here you can check the "Path to Executable" which should have a defaults-file switch which points to where your config file is.

    How to vertically center a container in Bootstrap?

    The Flexible box way

    Vertical alignment is now very simple by the use of Flexible box layout. Nowadays, this method is supported in a wide range of web browsers except Internet Explorer 8 & 9. Therefore we'd need to use some hacks/polyfills or different approaches for IE8/9.

    In the following I'll show you how to do that in only 3 lines of text (regardless of old flexbox syntax).

    Note: it's better to use an additional class instead of altering .jumbotron to achieve the vertical alignment. I'd use vertical-center class name for instance.

    Example Here (A Mirror on jsbin).

    <div class="jumbotron vertical-center"> <!-- 
                          ^--- Added class  -->
      <div class="container">
        ...
      </div>
    </div>
    
    .vertical-center {
      min-height: 100%;  /* Fallback for browsers do NOT support vh unit */
      min-height: 100vh; /* These two lines are counted as one :-)       */
    
      display: flex;
      align-items: center;
    }
    

    Important notes (Considered in the demo):

    1. A percentage values of height or min-height properties is relative to the height of the parent element, therefore you should specify the height of the parent explicitly.

    2. Vendor prefixed / old flexbox syntax omitted in the posted snippet due to brevity, but exist in the online example.

    3. In some of old web browsers such as Firefox 9 (in which I've tested), the flex container - .vertical-center in this case - won't take the available space inside the parent, therefore we need to specify the width property like: width: 100%.

    4. Also in some of web browsers as mentioned above, the flex item - .container in this case - may not appear at the center horizontally. It seems the applied left/right margin of auto doesn't have any effect on the flex item.
      Therefore we need to align it by box-pack / justify-content.

    For further details and/or vertical alignment of columns, you could refer to the topic below:


    The traditional way for legacy web browsers

    This is the old answer I wrote at the time I answered this question. This method has been discussed here and it's supposed to work in Internet Explorer 8 and 9 as well. I'll explain it in short:

    In inline flow, an inline level element can be aligned vertically to the middle by vertical-align: middle declaration. Spec from W3C:

    middle
    Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

    In cases that the parent - .vertical-center element in this case - has an explicit height, by any chance if we could have a child element having the exact same height of the parent, we would be able to move the baseline of the parent to the midpoint of the full-height child and surprisingly make our desired in-flow child - the .container - aligned to the center vertically.

    Getting all together

    That being said, we could create a full-height element within the .vertical-center by ::before or ::after pseudo elements and also change the default display type of it and the other child, the .container to inline-block.

    Then use vertical-align: middle; to align the inline elements vertically.

    Here you go:

    <div class="jumbotron vertical-center">
      <div class="container">
        ...
      </div>
    </div>
    
    .vertical-center {
      height:100%;
      width:100%;
    
      text-align: center;  /* align the inline(-block) elements horizontally */
      font: 0/0 a;         /* remove the gap between inline(-block) elements */
    }
    
    .vertical-center:before {    /* create a full-height inline block pseudo=element */
      content: " ";
      display: inline-block;
      vertical-align: middle;    /* vertical alignment of the inline element */
      height: 100%;
    }
    
    .vertical-center > .container {
      max-width: 100%;
    
      display: inline-block;
      vertical-align: middle;  /* vertical alignment of the inline element */
                               /* reset the font property */
      font: 16px/1 "Helvetica Neue", Helvetica, Arial, sans-serif;
    }
    

    WORKING DEMO.

    Also, to prevent unexpected issues in extra small screens, you can reset the height of the pseudo-element to auto or 0 or change its display type to none if needed so:

    @media (max-width: 768px) {
      .vertical-center:before {
        height: auto;
        /* Or */
        display: none;
      }
    }
    

    UPDATED DEMO

    And one more thing:

    If there are footer/header sections around the container, it's better to position that elements properly (relative, absolute? up to you.) and add a higher z-index value (for assurance) to keep them always on the top of the others.

    PHP __get and __set magic methods

    Intenta con:

    __GET($k){
     return $this->$k;
    }
    
    _SET($k,$v){
     return $this->$k = $v;
    }
    

    SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

    I finally found the problem. The error was not the good one.

    Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.

    The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

    Strange Bug, Hope it will help other people.

    Most recent previous business day in Python

    Why don't you try something like:

    lastBusDay = datetime.datetime.today()
    if datetime.date.weekday(lastBusDay) not in range(0,5):
        lastBusDay = 5